In: Advanced Math
Write a program to solve the boundary value problem ? ′′ = ? ′ + 2? + cos ? for ? ? [0, ?/2] with ?( 0) = 0.3, ?( ?/ 2) = 0.1. Check your numerical solution with actual using necessary plot.(MATLAB)
We have solved the given ODE for exact solution and then solved numerically using finite difference method. All calculations are done in MATLAB. (code attached).
Now we will solve this system of linear equations to find yi
MATLAB code:
function [x,y]=finite_difference_ODE(n)
% n=number of subintervals;
% therefore number of nodes is n+1;
x0=0; xn=pi/2;
y0=0.3; yn=0.1;
h=(xn-x0)/n;
x=x0:h:xn;
A=zeros(n+1,n+1); % coefficient matrix of the system Ay=b;
b=zeros(n+1,1); % b vector of the system Ay=b;
A(1,1)=1; A(end,end)=1;
b(1)=y0; b(end)=yn;
for i=2:n
x1=x(i);
temp1=1/(h^2); % coefficient of y_(i-1);
temp2=-2/(h^2)+1/h-2; % coefficient of y_(i);
temp3=1/(h^2)-1/h; % coefficient of y_(i+1);
A(i,(i-1):(i+1))=[temp1 temp2 temp3];
b(i)=cos(x1);
end
y=A\b; % solving the system;
% Exact solution
A1=[1 1; exp(-pi/2) exp(pi)];
b1=[0.6;0.2];
c1=A1\b1;
x1=x0:0.01:xn;
yexact=c1(1)*exp(-x1)+c1(2)*exp(2*x1)-0.1*(sin(x1)+3*cos(x1));
plot(x,y,x1,yexact,'--','LineWidth',2);
xlabel('t','fontsize',18);
ylabel('y(t)','fontsize',18);
legend('Numerical solution','Actual solution','fontsize',14)
title('Numerical solution vs Actual solution for
n=100','fontsize',18);
end