I am trying to model in MATLAB the temperature distribution inside a rectangular prism with boundary and initial conditions and heat equation I was trying to visualize 2D slices in the 3D shape. However, the simulation takes too long and when I try to change the time step, I get stability issues and the output visuals look weird and inconsistent. Is there a way to fix this? The code I used is below:
clear; clf;
rho = 1;
cp = 1;
k = 1;
alpha = rho / (cp * k);
Lx = 10;
Ly = 10;
Lz = 10;
Nx = 21; Nt = 35*60;
Ny = 21;
Nz = 21;
dx = Lx / (Nx - 1);
dy = Ly / (Ny - 1);
dz = Lz / (Nz - 1);
c = 1;
C = 0.1;
dt = C * dx / c;
Tn = zeros(Nx, Ny, Nz);
x = linspace(0, Lx, Nx);
y = linspace(0, Ly, Ny);
z = linspace(0, Lz, Nz);
[X, Y, Z] = meshgrid(x, y, z);
Tn(:, :, :) = 80;
t = 0;
Tn(1, :, :) = 350; Tn(end, :, :) = 350;
Tn(:, 1, :) = 350; Tn(:, end, :) = 350;
Tn(:, :, 1) = 350; Tn(:, :, end) = 350;
figure;
title(sprintf('Time = %f seconds', t));
for n = 1:Nt
Tc = Tn;
t = t + dt;
for i = 2:Nx - 1
for j = 2:Ny - 1
for k = 2:Nz - 1
Tn(i,j,k)=Tc(i,j,k) +...
dt * alpha *...
(((Tc(i+1,j,k) - 2*Tc(i,j,k) + Tc(i-1,j,k))/dx/dx)+...
((Tc(i,j+1,k) - 2*Tc(i,j,k) + Tc(i,j-1,k))/dy/dy)+...
((Tc(i,j,k+1) - 2*Tc(i,j,k) + Tc(i,j,k-1))/dz/dz));
end
end
end
% Display slices in the XZ plane
slice(X, Y, Z, Tn, [], Lx/2, []);
xlabel('X (inches)');
ylabel('Y (inches)');
zlabel('Z (inches)');
title(sprintf('Time = %f seconds', t));
% Pause for a short duration to visualize the changes
pause(0.1);
end
I was trying to get an image like this. However, the simulation takes too long and after a short time there does not seem to be any temperature change whatsoever. When I increase the time step, I get a weird result. Do I have to wait for the simulation to take its time? And are there inconsistencies or flaws in my implementation of the heat equation in MATLAB?