%%Matlab code for solving Finite difference method ode
clear all
close all
%all initial conditions
x_in=0; x_end=10;
y_in=-2; y_end=3;
%all step size
%step length
nn=9;
%step size
h=(x_end-x_in)/(nn+1);
%all x values
x=x_in:h:x_end;
%creating tridiagonal matrix
for i=1:nn
a=((5/h^2)+(1/h));
b=((-10/h^2)+10); c=((5/h^2)-(1/h));
%Creating A matrix
if i==1
A(i,i)=b;
A(i,i+1)=c;
elseif i==nn
A(i,i)=b;
A(i,i-1)=a;
else
A(i,i)=b;
A(i,i+1)=c;
A(i,i-1)=a;
end
%creating b
matrix
if i==1
bb(1)=0-y_in*a;
elseif i==nn
bb(i)=0-y_end*c;
else
bb(i)=0;
end
end
fprintf('\tFor h=%f\n',h)
fprintf('The A matrix can be written as
A=\n')
disp(A)
fprintf('\tThe b vector can be written as
b=\n')
disp(bb')
fprintf('Rank of A is %f\n',rank(A))
fprintf('Condition number of A
%f\n',cond(A))
%Changing the h value
fprintf('\n\tBy changing the h value to
0.02')
clear all
%all initial conditions
x_in=0; x_end=10;
y_in=-2; y_end=3;
%all step size
%step length
nn=99;
%step size
h=(x_end-x_in)/(nn+1);
%all x values
x=x_in:h:x_end;
%creating tridiagonal matrix
for i=1:nn
a=((5/h^2)+(1/h));
b=((-10/h^2)+10); c=((5/h^2)-(1/h));
%Creating A matrix
if i==1
A(i,i)=b;
A(i,i+1)=c;
elseif i==nn
A(i,i)=b;
A(i,i-1)=a;
else
A(i,i)=b;
A(i,i+1)=c;
A(i,i-1)=a;
end
%creating b
matrix
if i==1
bb(1)=0-y_in*a;
elseif i==nn
bb(i)=0-y_end*c;
else
bb(i)=0;
end
end
fprintf('\n\tFor h=%f\n',h)
fprintf('Rank of A is %f\n',rank(A))
fprintf('Condition number of A
%f\n',cond(A))
%All y values
yy=A\bb';
%numerical solutions
y_num(1)=y_in;
for i=1:length(yy)
y_num(1,i+1)=yy(i);
end
y_num(1,nn+2)=y_end;
%Exact solution
A=-2; B=2*cot(14)+(3*exp(-2))/sin(14);
y_ext=@(x)
exp(x/5)*((A*cos(7*x/5))+B*sin(7*x/5));
%loop for x values
for i=1:length(x)
yy_ext(1,i)=y_ext(x(i));
end
hold on
plot(x,y_num,'r--')
plot(x,yy_ext)
xlabel('x')
ylabel('y(x)')
title('x vs. y(x) plot')
legend('Numerical solution','Exact
solution')
%error in exact and numerical solution for
h=0.02
error=norm(y_num-yy_ext);
fprintf('error in exact and numerical solution
for h=%f is %f.\n',h,error)
%%%%%%%%%%%%%% End of Code
%%%%%%%%%%%%%%%%
Discretization, ODE solving, condition number. Consider the differential equation 5y"(x) - 2y'(x) +10y(x)0 on the interval x E [0,10] with boundary conditions y(0)2 and y (10) 3 we set up a f...