u = lamda; % Upper diagonal: coefficients of T(i+1)
s = lamda; % Subdiagonal: coefficients of T(i-1) D = -2*(1+lamda); % Main Diagonal: coefficients of T(i) % Boundary conditions and Initial Conditions T(1)=200; T(2:nx)=25; T(nx+1)=25; %IC Tn(1)=200; Tn(nx+1)=25; %BC
Temp(1,:)=T; % Store results for future use
for j=1:nt % Loop over time
t(j)=t0+j*dt; % Use column vectors to construct tridiagonal matrices A=D*diag(ones(nx-1,1))+ u*diag(ones(nx-2,1),1)+ s*diag(ones(nx-2,1),- 1); % construct b matrices for k=1:nx-1 b(k)=-lamda*T(k)-2*(1-lamda)*T(k+1)-lamda*T(k+2); end % note that b is row vector b(1)=-lamda*T(1)-2*(1-lamda)*T(2)-lamda*T(3)-lamda*Tn(1); b(end)=-lamda*T(nx-1)-2*(1-lamda)*T(nx)-lamda*T(nx+1)- 2*lamda*25*dx/54*200; A(4,3)=2*lamda; A(4,4)=-2*(1+lamda+lamda*25*dx/54); Y=A\b'; % Find the solution for interior nodes i=2,3,4,5 Tn(nx+1)=Y(end-1)-2*25*0.02*lamda/54*(Y(end)-200); Tn=[Tn(1),Y',Tn(nx+1)]; % Build the whole solution as row vector Temp(j+1,:)=Tn; % Store results for future use T=Tn; % to start over fprintf('t = %4.1f, T = %8.2f %8.2f %8.2f %8.2f %8.2f %8.2f\n',t(j),T) end x=[0:dx:L]'; t=[t0,t]'; subplot(1,2,1) surf(x,t,Temp) subplot(1,2,2) plot(x,Temp(2,:),'r*-'), hold on plot(x,Temp(3,:),'bo-') plot(x,Temp(4,:),'g*-') plot(x,Temp(5,:),'bo-') Output