MATLAB: Heat Conduction in 1D with Finite Differences

finite differencesheat conductionMATLAB

Hello. I want to plto/simulate the temperature distribution of the following equation and statements:
Here is my code:
clear
clc
clf
L =1; %length
alpha = 1;
xmin = 0;
xmax = L;
N = 100; %number of nodes
dx = (xmax-xmin)/(N-1);
x = xmin:dx:xmax;
x0 = 0:dx/2:L/2; %values of x for the firs line T0=2x
xL = L/2:dx/2:L; %values of x for the second line TL=2(1-x)
dt = 4.000E-5;
tmax = 1;
t = 0:dt:tmax;
% problem initialization
T0 = ones(1,N).*(2*x0);
TL = ones(1,N).*(2-2*xL);
% solving the problem
r = alpha*dt/(dx^2); % for stability, must be 0.5 or less
for j = 2:length(t) % for time steps
T = [T0 TL];
for i = 1:N % for space steps
if i == 1 || i == N
T(i) = 0;
else
T0(i) = T0(i)+r*(T0(i+1)-2*T0(i)+T0(i-1)); %values of temperature for 0 < x < L/2
TL(i) = TL(i)+r*(TL(i+1)-2*TL(i)+TL(i-1)); %values of temperature for L/2 < x < L
end
end
T = [T0 TL];
plot(x,T)
shg
pause(0.005)
end
Im having difficulty troubleshooting the code. I can't quite get x and T to be the same size in order to plot. I was hoping someone might shed some light on what be wrong. Thank you!

Best Answer

I have some suggestions to your code. Look
Related Question