PDEs via Finite Differences
Solve the 1D heat equation step-by-step using an explicit finite-difference scheme implemented with for-loops.
Step 1 — Discretise the domain
Divide the spatial interval [0, 1] into N cells of width dx, and choose a time step dt small enough to satisfy the stability condition dt ≤ dx²/2 (Courant–Friedrichs–Lewy criterion).
N = 20;
dx = 1 / N;
dt = 0.4 * dx^2;
x = linspace(0, 1, N+1);
printf('dx=%.3f, dt=%.6f, CFL ratio=%.2f\n', dx, dt, dt/dx^2)▶ Run in SimLabExpected output: dx=0.050, dt=0.001000, CFL ratio=0.40
Step 2 — Set initial condition and boundary conditions
Start with a Gaussian heat pulse centred at x=0.5. Dirichlet boundary conditions hold u(0) = u(1) = 0 (fixed cold ends).
N = 20;
dx = 1 / N;
x = linspace(0, 1, N+1);
u = exp(-200*(x - 0.5).^2);
u(1) = 0; u(end) = 0;
plot(x, u);
xlabel('x'); ylabel('u');
title('Initial heat pulse')▶ Run in SimLabExpected output: Sharp Gaussian pulse centred at x=0.5
Step 3 — Time-step the heat equation
Apply the explicit update rule u_new(i) = u(i) + dt/dx² * (u(i+1) - 2u(i) + u(i-1)) for 80 steps and plot the solution at several snapshots to watch the pulse diffuse.
N = 20; dx = 1/N; dt = 0.4*dx^2;
x = linspace(0, 1, N+1);
u = exp(-200*(x - 0.5).^2);
u(1) = 0; u(end) = 0;
hold on;
nSteps = 80;
r = dt / dx^2;
for step = 1:nSteps
u_new = u;
for i = 2:N
u_new(i) = u(i) + r*(u(i+1) - 2*u(i) + u(i-1));
end
u = u_new;
if mod(step, 20) == 0
plot(x, u);
end
end
xlabel('x'); ylabel('u');
title('Heat Diffusion at t=0.02, 0.04, 0.06, 0.08')▶ Run in SimLabExpected output: Four curves showing the pulse spreading and flattening over time
Related Tutorials
Try SimLab — MATLAB®-compatible, free, in your browser
466 functions. Runs in your browser. No install.
Open SimLabMATLAB® is a registered trademark of The MathWorks, Inc. SimLab is an independent project by Simulations4All and is not affiliated with, endorsed by, or sponsored by The MathWorks, Inc.