%% Crank-Nicolson Method
clear variables
close all
% 1. Space steps
xa = 0;
xb = 1;
dx = 1/40;
N = (xb-xa)/dx ;
x = xa:dx:xb;
%2.Time steps
ta = 0;
tb = 0.5;
dt = 1/3300;
M = (tb-ta)/dt ;
t = ta:dt:tb;
%3. Controling Parameters
%4. Define equations A, B , C and phi(x,t)
A = @(x,t) (50/3)*(x-0.5+4.95*t);
B = @(x,t) (250/3)*(x-0.5+0.75*t);
C = @(x,t) (500/3)*(x-0.375);
phi = @(x,t)(0.1*exp(-A(x,t)) +0.5*exp(-B(x,t))+exp(-C(x,t)))./...
(exp(-A(x,t)) +exp(-B(x,t))+exp(-C(x,t)));
% 5 Initial and boundary conditions
f = @(x) phi(x,t(1)); % Initial condition
g1 = @(t)phi(x(1),t); % Left boundary condition
g2 = @(t)phi(x(N+1),t); % Right boundary condition
r = dt / (2*dx^2);
a = -0.003*r;
b = 1 + 2*0.003*r;
c = -r*0.003;
d =(1+0.003*2*r);
e =1+0.003*2*r;
h =0.003*r;
% 6 Implementation of the explicit method
U = zeros(N+1,M+1);
U(2:N,1) = f(x(2:N)); % Put in the initial condition
U(1,:) = g1(t); % The boundary conditions, g1 and g2 at x = 0 and x = 1
U(N+1,:) = g2(t);
for i = 2:N
RHS= (1+2*0.003*r)*U(i,N)+0.003*r*U(i+1,N)+0.003*r*U(i-1,N)-r*dx*U(i,N)*(U(i,N)-U(i-1,N));
end
for j=2:M % Time Loop
for i= 2:N % Space Loop
RHS= (1+2*0.003*r)*U(i,N+1)+0.003*r*U(i+1,N+1)+0.003*r*U(i-1,N+1)-r*dx*U(i,N+1)*(U(i,N+1)-U(i-1,N+1));
end
end
% Make some plots
T= 0:.1:M;
V = [];
for i= 1: length(T)
P = find(t==T(i));
V = [V P];
end
figure
subplot(131)
for j = 1:length(V)
hold on
plot(x,U(:,V(j)),'*-','linewidth',2.5,'DisplayName',sprintf('t = %1.4f',t(V(j))))
end
legend('-DynamicLegend','location','bestoutside');
a = ylabel('U-Values');
set(a,'Fontsize',14);
a = xlabel('X-Values');
set(a,'Fontsize',14);
a=title('Crank-Nicolson Solution');
set(a,'Fontsize',16);
grid;
% disp(u(:,V)'); % Each row corresponds to a particular value of t and
% Each column corresponds to a particular value of x
% Implement the exact solution and compare it to the exact solution
Exact =@(x,t) phi(x,t);
subplot(132)
for j = 1:length(V)
hold on
plot(x,Exact(x,t(V(j))),'*-','linewidth',2.5,'DisplayName',sprintf('t = %1.4f',t(V(j))))
end
legend('-DynamicLegend','location','bestoutside');
a = ylabel('U-Values');
set(a,'Fontsize',14);
a = xlabel('X-Values');
set(a,'Fontsize',14);
a=title(' Analytical Solution');
set(a,'Fontsize',16);
grid;
[X,T] = meshgrid(x,t);
% Exact2 = (0.1*exp(-A(X,T)) +0.5*exp(-B(X,T))+exp(-C(X,T)))./...
% (exp(-A(X,T)) +exp(-B(X,T))+exp(-C(X,T)));
Error =abs(Exact(X,T)'-U);
subplot(133)
for j = 1:length(V)
hold on
plot(x,Error(:,(V(j))),'*-','linewidth',2.5,'DisplayName',sprintf('t = %1.4f',t(V(j))))
end
legend('-DynamicLegend','location','bestoutside');
a = ylabel('Error');
set(a,'Fontsize',14);
a = xlabel('X-Values');
set(a,'Fontsize',14);
a=title(' Absolute Error ');
set(a,'Fontsize',16);
grid;