Matlab program with the Crank-Nicholson method

Matlab program with the Crank-Nicholson method for the diffusion equation

https://www.youtube.com/watch?v=HiCdEG7uw7E

%Heat diffusion in one dimension wire within

%Parameters to define the heat equation
cond = 1/2;   % Heat conductivity parameter
L = 1.;       % Length of the wire
T = 1.;       % Final Time

%Parametes for Crank-Nocholson
Nt = 2500;          % Number of time steps
Dt = T/Nt;
Nx = 50;            % Number of space steps
Dx = L/Nx;
b = cond*Dt/(Dx*Dx);% Alpha Value

%Initial Condition
for n = 1:Nx-1
    x(n) = (n-1)*Dx;
    u(n,1) = sin(pi*x(n));
end

%Boundary Condition
for j = 1:Nt+1
    u(1,j) = 0.;  % Boundary is 0 for any moment
    u(Nx+1,j) = 0.;
    t(j) = (j-1)*Dt;
end

%Defining the M_right and M_left matrices in Crank method
% As mmr matrices are tridiagonal we first define the three diagonals
% and then build the matrices

aal(1:Nx-2) = -b;                      %Below the main diagonal in MML
bbl(1:Nx-1) = 2.+2.*b;                 % The main diagonal in MML
ccl(1:Nx-2) = -b;                      %Abpve
MMl = diag(bbl,0) + diag(aal,-1)+diag(ccl,1);


aar(1:Nx-2) = b;                      %Below the main diagonal in MML
bbr(1:Nx-1) = 2.-2.*b;                 % The main diagonal in MML
ccr(1:Nx-2) = b;                      %Abpve
MMR = diag(bbr,0) + diag(aar,-1)+diag(ccr,1);

%Crank
for j = 1:Nt
    u(2:Nx,j+1) = inv(MML) * MMR * u(2:Nx,j);
end

figure(1);
plot(x,u(:,1),'-b');
plot(x,u(:,round(Nt/100)),'-g');
plot(x,u(:,round(Nt/10)),':b');
plot(x,u(:,Nt),'-.r');

xlabel('X');
ylabel('T');

figure(2);
mesh(t,x,u);
xlabel('t');
ylabel('x');

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值