Problem with function handle

2 Ansichten (letzte 30 Tage)
Salih Bulut
Salih Bulut am 18 Jun. 2020
Beantwortet: Vinayak Mohite am 18 Jun. 2020
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 %%%%%%%

Akzeptierte Antwort

James Tursa
James Tursa am 18 Jun. 2020
f by itself is just a function handle, not the function handle evaluated for any input. You need to give f an input. E.g.,
b= M * f(x) * dx^2 / 6;

Weitere Antworten (1)

Vinayak Mohite
Vinayak Mohite am 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.

Kategorien

Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by