Heat Conduction in 1D with Finite Differences

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!

 Accepted Answer

I have some suggestions to your code. Look

3 Comments

It worked wonderfully! I forgot to add it to the question but, can you help with using a mesh to plot the temperature through time and space? Can it be done in this case?
Sure, here is an example
T = [T0 TL]; % X direction (columns)
T = repmat(T,[100 1]); % make 100 points in time direction (rows)
h = surf(T); % display
for i = 1:size(T,1)-1
for j = 2:size(T,2)-1
T(i+1,j) = T(i,j) + r*(T(i,j+1)-2*T(i,j)+T(i,j-1));
end
set(h,'zdata',T)
pause(0.01)
end
Pay attention that im not plotting inside for loop. Only changing z data inside. It's much faster

Sign in to comment.

More Answers (0)

Products

Release

R2018b

Asked:

on 26 Apr 2020

Commented:

on 27 Apr 2020

Community Treasure Hunt

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

Start Hunting!