A second order linear differential equation was solved by the analytical and numerical approach. Finite difference method was used to discretize the differential equation. A second order central difference scheme with four different meshes (N = 6, 11, 21, 41) was used. The discretized equations were solved by tridiagonal matrix inversion (TDMI) algorithm. A Dirichlet-type boundary condition was used at the boundary nodes. Figure 1(a) shows the analytical solution where is phi plotted as a function of x. Figure 1 shows the numerical solution (N = 11 case only) and compared with the analytical solution.
MATLAB Code
%% Tridiagonal Matrix Algorithm
% Arif Hossain - 01/19/2017
clc; clear all; close all;
mesh = [6 11 21 41];
for j = 1:length(mesh)
% Analytic Calculation
c1 = 2-exp(-1);
c2 = -1;
x_any = linspace (0,1,100);
phi_any = exp(-x_any)+c1*x_any+c2;
% Numerical calculation
N = mesh(j);
L = 1;
delX = L/(N-1);
x = (0:delX:L);
D = [1, -2*ones(1,N-2), 1];
C = [0, 1*ones(1,N-2)];
A = [1*ones(1,N-2), 0];
B(1) = 0;B(N) = 1;
phi(1) = 0;
for i = 2:N-1
B(i) = (delX.^2)*exp(-i*delX);
end
for i = 2:N-1
xmult = A(i-1)/D(i-1);
D(i) = D(i)-xmult*C(i-1);
B(i) = B(i)-xmult*B(i-1);
end
phi(N) = B(N)/D(N);
for i = N-1:-1:1
phi(i) = (B(i)-C(i)*phi(i+1))/D(i);
end
% Figure
figure()
plot(x_any,phi_any,'-r','linewidth',2)
hold on
plot(x,phi,'sb','linewidth',2)
set(gca,'fontsize',14,'fontweight','bold')
xlabel('x');ylabel('\phi(x)');grid on
legend('Analytic sol^n','Numeric Sol^n (TDMA)','location','southeast')
% Error calculation
for i = 1:N
phi_any(i) = exp(-x(i))+c1*x(i)+c2;
err(i,j) = abs((phi_any(i)-phi(i))/phi_any(i))*100;
end
figure(2)
plot(x,err(:,j),'--s','linewidth',2)
set(gca,'fontsize',14,'fontweight','bold')
xlabel('x');ylabel('E(x)');grid on
hold on
end