Problem with function handle
Show older comments
The first M-file contains:
function z = FEM1D(f, N)
%%%%%%%%%%%%%%%%%%
dx=0.1;
x=[0:dx:1]';
N=length(x);
%Matrix
A=-2*diag(ones(N,1));
M=4*diag(ones(N,1));
%Filling matrix
for i=1:N-1
A(i,i+1)=1;
A(i+1,i)=1;
M(i,i+1)=1;
M(i+1,i)=1;
end
%%%%%% HERE THE PROBLEM HAPPENS %%%%%%%
b= M*f*dx^2/6;
%boundary
A(1,:)=0;
A(1,1)=1;
A(N,:)=0;
A(N,N)=1;
b(1)= 0; %left boundary
b(N)= 0; %right boundary
%result
z=A\b;
end
The function z = FEM1D(f, N) is called from this M-file:
tol_max = 1e-10;
N = 10;
%%%%%%%%%%%%%%%%%% example 1:
f_1 = @(x)(1-x); % right side
sol_1 = @(x) -1/6*x.*(2 - 3*x + x.^2); % excat result
%%%%%%%%%%%%%%%%%% example 2:
a=0.5;
c=100;
f_2 = @(x) c*(2*(2*a^2*c - 4*a*c*x + 2*c.*x.^2 - 1).*exp(-a^2*c + 2*a*c*x - c*x.^2));
sol_2 = @(x) (exp(-(x-a).^2*c) - exp(-(a).^2*c));
%%%%%%%%%%%%%%%%%% solve example 1:
z_1 = FEM1D(f_1 , N);
x = linspace(0,1,N+1);
sol_dis_1 = sol_1(x)';
err = max(z_1 - sol_dis_1);
if(abs(err) > tol_max)
error('error example 1')
z_1 - sol_dis_1
end
%%%%%%%%%%%%%%%%%% solve example 2:
z_2 = FEM1D(f_2 , N);
x = linspace(0,1,N+1);
sol_dis_2 = sol_2(x)';
err = max(z_2 - sol_dis_2);
if(abs(err) > tol_max)
error('error example 2')
z_2 - sol_dis_2
end
disp('code is okey')
What do I have to change in the first file to make the second file work? The line in the first file where the error happens I' ve marked with
%%%%%% HERE THE PROBLEM HAPPENS %%%%%%%
Accepted Answer
More Answers (1)
Vinayak Mohite
on 18 Jun 2020
Hi Salih,
The problem in your code is one cannot multiply the function handle with a scalar. Consider passing a parameter to the function handle.
e.g. change
b= M*f*dx^2/6;
to
b= M*f(-11)*dx^2/6;
You can use any value instead of -11.
Categories
Find more on Creating, Deleting, and Querying Graphics Objects in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!