Construct Thomas Construct Initial Condition Crank-Nicolson: While
Construct Thomas Construct Initial Condition Crank-Nicolson: While
Contents
Construct Thomas
Construct Initial condition
Crank–Nicolson
L=1;
b_coe=1;
n=201;
coord_x=linspace(0,L,n);
% dx=L/(n-1);
% dt=0.5*dx^2;
% dt=5*dx^2;
% dt=50*dx^2;
T=0.5;
Construct Thomas
mu=b_coe*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)
%%%%%%%%%%%%%%%%%%
a=[0;amat];
b=bmat;
c=[cmat;0];
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;
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)';
file:///G:/我的雲端硬碟/NumericalMethod/Project3/html/CodeA.html 1/2
2019/11/4 CodeA
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=x(:,end);
% figure
% plot(coord_x,x_end(:,1),'r')
file:///G:/我的雲端硬碟/NumericalMethod/Project3/html/CodeA.html 2/2