1D heat equation finite difference code improvement
33 views (last 30 days)
Show older comments
I'm trying to solve a problem of a 1D heat equation using finite difference. I just would like to know if this code is well-written or can be improved?
Any help will be appreciated.
clear; clc; close all;
L = 1;
N = 5; % number of interior nodes
T0 = 100; % boundary at x=0
Tend = 200; % boundary at x=L
h = L/(N+1); % grid spacing
x_interior = (1:N)*h; % interior x positions
e = ones(N,1);
A = (1/h^2) * spdiags([e -2*e e], -1:1, N, N);
b = zeros(N,1);
b(1) = -T0 / h^2;
b(end) = -Tend / h^2;
T_interior = A \ b;
x_full = [0; x_interior'; L]';
T_full = [T0; T_interior; Tend];
fprintf('Grid spacing h = %.6f\n', h);
fprintf('Interior positions and temperatures:\n');
for i = 1:N
fprintf(' x = %.6f, T_%d = %.6f\n', x_interior(i), i, T_interior(i));
end
fprintf('\nFull solution (including boundaries):\n');
for i = 1:length(x_full)
fprintf(' x = %.6f, T = %.6f\n', x_full(i), T_full(i));
end
figure;
plot(x_full, T_full, '-o', 'LineWidth', 1.4);
xlabel('x (m)');
ylabel('Temperature (^\circC)');
title('Steady-state 1D heat: finite-difference solution (N=5 interior)');
grid on;
T_analytic = 100 + 100*x_full; % since T(x) = 100 + 100 x
fprintf('\nAnalytic (linear) solution at grid points:\n');
for i=1:length(x_full)
fprintf(' x = %.6f, T_analytic = %.6f\n', x_full(i), T_analytic(i));
end
3 Comments
Torsten
on 13 Dec 2025 at 1:27
I know this, and it is correct.
I only suggested to include the temperatures in the boundary points in the matrix A to make the equations more transparent:
T0 = 100;
Tend = 200;
A = [1 0 0 0 0 0 0;
1 -2 1 0 0 0 0;
0 1 -2 1 0 0 0;
0 0 1 -2 1 0 0;
0 0 0 1 -2 1 0;
0 0 0 0 1 -2 1;
0 0 0 0 0 0 1];
b = [T0;0;0;0;0;0;Tend];
T = A\b
Answers (1)
Ayush
on 16 Dec 2025 at 6:05
Hi Cesar,
Your code seems correct and efficiently solves for the interior temperatures by incorporating the boundary conditions into the right-hand side vector.
Alternatively, as discussed in comments, you could include the boundary temperatures as unknowns and set up a larger system where the boundary conditions appear directly as equations in the matrix. This makes the system more transparent and the boundary values explicit in the solution vector, but is less common for numerical efficiency.
Both methods are valid and should yield the same temperature distribution along the rod.
Hope this helps!
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!