I am trying to solve a second order ODE using Finite difference method.I have written a code as below but it shows error upon running.Can anyone help me find the potential error in my code.Thanks

function [x,U]=FD(a,b,ua,uxb,f,n)
a=0;b=10;n=100;
h=(b-a)/n;
h1=h*h;
A=sparse(n-1,n-1);
F=zeros(n-1,1);
for i=1:n-2
A(i,i)=-2/h1;A(i+1,i)=1/h1;A(i,i+1)=1/h1;
end
A(n-1,n-1)=-2/h1;
for i=1:n-1
x(i)=a+i*h;
f=0.091875*cos(x(i));
F(i)=feval(f,x(i));
end
F(1)=F(1)-ua/h1;
F(n-1)=F(n-1)-uxb/hi;
U=A/F;
a=0;b=10;n=100;
ua=0;uxb=0;
[x,U]=FD(a,b,ua,uxb,'f',n);
plot(x,U,0);hold
u=zeros(n-1,1);
for i=1:n-1,
u(i)=0.091875*cos(x(i));
end
plot(x,u)
The error shown to be as ;
Error using feval
Argument must contain a string or function_handle.
Error in FD (line 14)
F(i)=feval(f,x(i));

 Accepted Answer

f=@(x)0.091875*cos(x);
F(i)=feval(f,x(i));
Best wishes
Torsten.

3 Comments

Hi,
It shows me this error
Error using FD (line 16) Not enough input arguments.(for the below line)
"F(1)=F(1)-ua/h1"
Thanks
I tried it again,It showing a error something like,
Maximum recursion limit of 500 reached. Use set(0,'RecursionLimit',N) to change the limit. Be aware that exceeding your available stack space can crash MATLAB and/or your computer.
Thanks
Save the function FD in a separate script. Otherwise, you call FD recursively with the call
[x,U]=FD(a,b,ua,uxb,'f',n);
at the end of the program.
Best wishes
Torsten.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements 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!