Crank Nicolson (Matlab) PDF
Crank Nicolson (Matlab) PDF
(Wavethomasalg.m)
function x=wavethomasalg(C,D,E,B)
%Filname:thomasalg.m
%input
% c subdiagonal of A
% d maindiagonal of A
% e superdiagonal of A
%output
%x solution of Ax=b
n=length(D);
alpha=zeros(n,1);
beta=zeros(n-1,1);
alpha(1)=D(1);
beta(1)=E(1)/alpha(1);
for i=2:n-1
alpha(i)=D(i)-C(i-1)*beta(i-1);
beta(i)=E(i)/alpha(i);
end;
alpha(n)=D(n)-C(n-1)*beta(n-1);
w(i)=(B(i)-C(i-1)*w(i-1))/alpha(i);
end;
%Backward substitution to solve Ux=w
x=zeros(n,1);
x(n)=w(n);
for i=n-1:-1:1
x(i)=w(i)-beta(i)*x(i+1);
end;
(Hyperwavecrankthomas_in)
%INPUT
%Filename: hypwavecrankthomas_in.m
clc
c=1; %coefficient in PDE;
L=3.142; %length of string in x
Tmax=1; %maxmimum time t
h=0.3142; %step size for space x
k=0.05; %step size for space t
delta=1; %value of delta
r=k/h;
%(c)C.R.C.Teh
%OUTPUT
%u matrix of solution value
%Crank-Nicolson method
r=k/h;
for j=3:M
for i=1:N-2
D1(i)=2*(1+r^2);
D2(i)=2+2*c^2*r^2;
end;
for i=1:N-3
C1(i)=-r^2;
C2(i)=-r^2;
E1(i)=-r^2;
E2(i)=-r^2;
end;
for i=2:N-1
if i==1
B1(i)=2*r^2*u(1,j-1)-(2+2*r^2)*u(i,j-1)+r^2*u(i+1,j-1)+4*u(i,j)-
2*k^2*delta^2*sin(u(i,j)-w(i,j));
B2(i)=2*c^2*r^2*w(1,j-1)-(2+2*c^2*r^2)*w(i,j-1)+c^2*r^2*w(i+1,j-
1)+4*w(i,j)+2*k^2*sin(u(i,j)-w(i,j));
else
if i==N-1
B1(i)=2*r^2*u(N,j-1)+r^2*u(i-1,j-1)-(2+2*r^2)*u(i,j-1)+4*u(i,j)-
2*k^2*delta^2*sin(u(i,j)-w(i,j));
B2(i)=2*c^2*r^2*w(N,j-1)+r^2*w(i-1,j-1)-(2+2*c^2*r^2)*w(i,j-
1)+4*w(i,j)+2*k^2*sin(u(i,j)-w(i,j));
else
B1(i)=r^2*u(i-1,j-1)-(2+2*r^2)*u(i,j-1)+r^2*u(i+1,j-1)+4*u(i,j)-
2*k^2*delta^2*sin(u(i,j)-w(i,j));
B2(i)=c^2*r^2*w(i-1,j-1)-(2+2*c^2*r^2)*w(i,j-1)+c^2*r^2*w(i+1,j-
1)+4*w(i,j)+2*k^2*sin(u(i,j)-w(i,j));
end
end
for ii=1:N-2
BB1(ii)=B1(ii+1);
BB2(ii)=B2(ii+1);
end
aa=wavethomasalg2(C1,D1,E1,BB1);
for ii=2:N-1
u(i,j)=aa(ii-1);
end
bb=wavethomasalg2(C2,D2,E2,BB2);
for ii=2:N-1
w(i,j)=bb(ii-1);
end
end
end
disp('--------------------------------------')
fprintf(' u=x\\t')
fprintf(' %4,2f ',t)
fprintf('\n')
disp('--------------------------------------')
for i=1:N
fprintf(' %4.4f',x(i))
for j=1:M
fprintf('%10.4f',u(i,j))
end
fprintf('\n')
end
disp('--------------------------------------')
fprintf(' w=x\\t')
fprintf(' %4,2f ',t)
fprintf('\n')
disp('--------------------------------------')
for i=1:N
fprintf(' %4.4f',x(i))
for j=1:M
fprintf('%10.4f',w(i,j))
end
fprintf('\n')
end