You are on page 1of 4

2019/11/4 Prob2

Contents
Construct Thomas
Construct Initial condition
Crank–Nicolson

close all
clear all
for k=1:3

L=1;
b=1;
n=201;
coord_x=linspace(0,L,n);
dx=L/(n-1);
if k==1
dt=0.5*dx^2;
elseif k==2
dt=5*dx^2;
else
dt=50*dx^2;
end
restore_dt(k)=dt;
T=0.5;

Construct Thomas

mu=b*dt/(dx^2);
bmat=(1+mu)*ones(n,1);
amat=-0.5*mu.*ones(n-1,1);%note amat and cmat are shorter than bmat
cmat=-0.5*mu.*ones(n-1,1);
%
%in the lines below, I am modifying the matrix to be more consistent with
%a discrete heat equation with first type B.C.
c1=1;c2=0;c3=0;c4=1;
amat(n-1,1)=-c4/dx;
cmat(1,1)=c2/dx;
bmat(1,1)=c1-c2/dx;
bmat(n,1)=c3+c4/dx;
%
A=diag(bmat)+diag(amat,-1)+diag(cmat,1);
%this command shows the locations of non-zero elements in a matrix
% spy(A)
%%%%%%%%%%%%%%%%%%
%to use the thomas function, we need the same lengths for the a,b and c vectors,
%so we need to redefine the above a,b and c vectors:
%put "0" at the start of a and at the end of c. Then call thomas
a=[0;amat];
b=bmat;
c=[cmat;0];

Construct Initial condition

f1=c1*1+c2*0;
f2=c3*0+c4*0;
x_ini=zeros(n,1);
r=zeros(n,1);
x_ini(1)=1;x_ini(end)=0;
file:///G:/我的雲端硬碟/NumericalMethod/Project3/html/Prob2.html 1/4
2019/11/4 Prob2
x=x_ini;
r(1)=f1;r(end)=f2;
r(2:n-1,1)=0.5*mu*x_ini(1:n-2,1)+(1-mu)*x_ini(2:n-1,1)+0.5*mu*x_ini(3:n,1);
t=0;
i=1;

Crank–Nicolson

while t <= T
i=i+1;
t=t+dt;
x_next=thomas2019(a,b,c,r)';
x(:,i)=x_next;
r(2:n-1,1)=0.5*mu*x_next(1:n-2,1)+(1-mu)*x_next(2:n-1,1)+0.5*mu*x_next(3:n,1);
end
x_end(:,k)=x(:,end);
X=[];
r=[];

end

theta0=1;alpha=1;L=1;
t=[0.01 0.1 0.2 0.5]; x=0:0.005:1;
for i=1:length(t)
for ii=1:length(x)
for n=0:100
theta(n+1,ii)=sin((2*n+1)*pi*x(ii)/2/L)*exp(-(((2*n+1)*pi)^2)*alpha*t(i)/4/L/L)/(2*n+1)/pi;
end
end
Theta(i,:)=theta0-4*theta0*sum(theta);
end
error=abs(x_end(101,:)-Theta(4,101))

error =

0.0011 0.0012 0.0019

figure
hold on
plot(x,Theta(4,:),'k','linewidth',5)
plot(coord_x,x_end(:,1),'.r','markersize',15)
plot(coord_x(1:10:end),x_end(1:10:end,2),'--b','linewidth',3)
plot(coord_x(1:20:end),x_end(1:20:end,3),'*g','linewidth',1)
legend('Analytical solution','dt=0.5*dx^2','dt=5*dx^2','dt=50*dx^2')
xlabel('Distance')
ylabel('u')

file:///G:/我的雲端硬碟/NumericalMethod/Project3/html/Prob2.html 2/4
2019/11/4 Prob2

figure
subplot(2,1,1)
hold on
plot(0.5,x_end(end,1),'*r','linewidth',1.5,'markersize',15)
plot(0.5,x_end(end,2),'^b','linewidth',3,'markersize',15)
plot(0.5,x_end(end,3),'og','linewidth',3,'markersize',15)
plot(0.5,Theta(4,end),'sk','linewidth',3,'markersize',10)
legend('dt=0.5*dx^2','dt=5*dx^2','dt=50*dx^2','Analytical solution')
ylim([0.625 0.635])
xlabel('t')
ylabel('u')
title('x = 1, t = 0.5')
subplot(2,1,2)
plot(restore_dt,error,'-p','linewidth',3)
xlabel('dt')
ylabel('error')
title('x = 0.5, t = 0.5')

file:///G:/我的雲端硬碟/NumericalMethod/Project3/html/Prob2.html 3/4
2019/11/4 Prob2

Published with MATLAB® R2018b

file:///G:/我的雲端硬碟/NumericalMethod/Project3/html/Prob2.html 4/4

You might also like