Clear Filters
Clear Filters

matlab code for crank nicolson scheme of finite difference method

21 views (last 30 days)
Dear sir,
I am trying to solve the finite difference methof for crank nicolson scheme to 2d heat equation. please let me know if you have any MATLAB CODE for this
boundary condition are
If you can kindly send me the matlab code, it will be very useful for my research work . thank you very much.
below is the code i tried. kindly correct the code for given the FDs
clear all; clc;
L = 1.;
T =1.;
maxk = 1500; % Number of time steps
dt = T/maxk;
n = 16; % Number of space steps
dx =0.5
dy =0.5
nn=3
mm=3
X=1
M=0.5
N=0.4
for i = 1:n;
for j = 1:n;
x(i) =(i-1)*dx;
Uk(i,j,1) =0;
Vk(i,j,1) =5;
Ck(i,j,1) =5;
Tk(i,j,1) =50;
end
end
% % Temperature at the boundary (T=0)
for k=1:maxk;
for j=1:n-1;
Uk(1,j,k) = 0;%sin(i*j);
Vk(1,j,k)= 0;
Tk(1,j,k)= 0;
Ck(1,j,k)= 0;
Uk(n+1,j,k) = 0;
Vk(n+1,j,k) = 0;
Tk(i,j+1,k+1)=Tk(i,j-1,k+1)+Tk(i,j+1,k)-Tk(i,j-1,k)+(x(j).^nn)*4*dy;
Ck(i,j+1,k+1)=Ck(i,j-1,k+1)+Ck(i,j+1,k)-Ck(i,j-1,k)+(x(j).^mm)*4*dy;
% Tk(n+1,j,k) = i*j
% Ck(n+1,j,k) = 50.;
time(k) = (k-1)*dt;
end
end
% Implementation of the explicit method
for k=1:maxk-1 % Time Loop
for i=2:n-1; % Space Loop
for j=2:n-1;
Uk(i,j,k)= Uk(i,j-1,k+1).*[-Vk(i,j,k).*dt/4.*dy-dt/2.*dy.*dy]...
+Uk(i,j,k+1).*(1+Uk(i,j,k).*dt/2.*dx+dt/dy.*dy+M.*dt/2)...
+Uk(i,j+1,k+1).*[Vk(i,j,k).*dt/4.*dy-dt/2.*dy^2]...
+Uk(i,j,k).*[((Uk(i-1,j,k+1)-Uk(i,j,k)+Uk(i-1,j,k)).*dt)/2.*dx]...
-Vk(i,j,k).*[((Uk(i,j-1,k)-Uk(i,j+1,k)).*dt)/4.*dy]...
-[((Tk(i,j,k+1)+Tk(i,j,k))/2+ N.*(Ck(i,j,k+1)+Ck(i,j,k))/2).*dt].*cos(pi)...
+[(( Uk(i,j-1,k)-2.* Uk(i,j,k)+ Uk(i,j+1,k))/2.*dy.*dy).*dt]...
+M.* Uk(i,j,k);
end
end
%Uk(i+1,j+1,k+1)=Uk(i,j,k)+dx*m
end
% Graphical representation of the temperature at different selected times
figure(1)
plot(x,Uk(:,:,1),'-r',x,Uk(:,:,3),'-b',x,Uk(:,:,5),'-y',x,Uk(:,:,10),'-g')
  1 Comment
NOUFA
NOUFA on 2 Oct 2021
Edited: NOUFA on 2 Oct 2021
Dear Sir,
if you know about how to solve the finite difference methof for crank nicolson scheme to1d heat equation. please let me know if you have any CODE for this.
many thanks

Sign in to comment.

Answers (1)

priya m priya m
priya m priya m on 5 Oct 2022
Sir, have you got error in above code corrected? if corrected kindly share the corrected code , it would be helpful for me.
  1 Comment
priya m priya m
priya m priya m on 5 Oct 2022
Sir, have you got error in above code corrected? if corrected kindly share the corrected code , it would be helpful for me.

Sign in to comment.

Categories

Find more on Programming in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!