Trouble implementing crank nicolson scheme for 1D Diffusion Equation

3 views (last 30 days)
Hi Folks, I am having issues coding up a piece of code I've written. It is the Diuffusion Equation with periodic boundary conditions using the crank nicolson scheme. I've given it a good amount of time and keep getting this error message:
Error using \ Matrix dimensions must agree.
Error in heat_cn (line 39) u(1:N-1,j+1) = A\RHS;
To be specific it has to do with solving the equation at each time step. Would really appreciate some help and guidance on this. Thanks!
function [u,err,x,t] = heat_cn(t_0,t_f,M,N)
% define the mesh in space
dx = 1/(N-1);
x = 0:dx:1;
x = x';
% define the mesh in time
dt = (t_f-t_0)/M;
t = t_0:dt:t_f;
% define the ratio r
r = dt/dx^2
for i=1:N
u(i,1) = sin(x(i));
end
err(:,1) = u(:,1) - exp(-t(1))*cos(x);
A = zeros(N-1,N-1);
A(1,1) = 1+r;
A(1,2) = -r/2;
A(1,N-1) = -r/2;
for i=2:N-2
A(i,i-1) = -r/2;
A(i,i) = 1+r;
A(i,i+1) = -r/2;
end
A(N-1,N-1) = 1+r;
A(N-1,N-2) = -r/2;
A(N-1,1) = -r/2;
for j=1:M
RHS(1) = u(1,j) + r/2*(u(2,j)-2*u(1,j)+u(N-1,j));
for i=2:N-1
RHS(i) = u(i,j) + r/2*(u(i+1,j)-2*u(i,j)+u(i-1,j));
end
u(1:N-1,j+1) = A\RHS;
% impose periodicity
u(N,j+1) = u(1,j+1);
err(:,j+1) = u(:,j+1) - exp(-t(j+1))*cos(x);
end
plot(x,u(:,3));

Answers (0)

Categories

Find more on Thermal Analysis 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!