clear; clc; close all;
%% ====== Problem Setup ======
Nx_nodes = 101; % Number of grid points (0 to 100 inclusive)
x_length = 100; % Total length
dx_step = 1.0; % Grid spacing
time_steps = 5000; % Simulation steps
dt_step = 0.05; % Time step size
k_left = 1.0; % Conductivity in left half
k_right = 5.0; % Conductivity in right half
x_split = 50; % Position of material interface
T_LBC = 500; % Left boundary temperature
T_RBC = 100; % Right boundary temperature
%% ====== Initial Temperature Field ======
Temp = zeros(Nx_nodes, time_steps);
Temp(:,1) = 300; % Initial guess
Temp(1,1) = T_LBC;
Temp(end,1) = T_RBC;
%% ====== Explicit Time Marching ======
for n = 1:(time_steps-1)
for p = 2:(Nx_nodes-1)
xpos = (p-1); % Actual coordinate
% Left conductivity (half step)
if xpos-1 < x_split
k_mhalf = k_left;
else
k_mhalf = k_right;
end
% Right conductivity (half step)
if xpos < x_split
k_phalf = k_left;
else
k_phalf = k_right;
end
% Temperature update (explicit scheme)
Temp(p, n+1) = Temp(p, n) + dt_step/(dx_step^2) * ...
( k_phalf * (Temp(p+1, n) - Temp(p, n)) ...
- k_mhalf * (Temp(p, n) - Temp(p-1, n)) );
end
% Boundary conditions
Temp(1, n+1) = T_LBC;
Temp(end, n+1) = T_RBC;
1
end
%% ====== Analytic Steady-State Solution ======
x_grid = 0:dx_step:x_length;
% Thermal resistances
R_left = x_split / k_left;
R_right = (x_length - x_split) / k_right;
R_tot = R_left + R_right;
% Steady flux (positive left→right)
q_flux = (T_LBC - T_RBC) / R_tot; % will be 20/3
fprintf('Steady-state heat flux q = %.5f\n', q_flux);
Steady-state heat flux q = 6.66667
% Interface temperature
T_int = T_LBC - (q_flux / k_left) * x_split;
% Piecewise analytic profile
T_exact = zeros(size(x_grid));
T_exact(x_grid <= x_split) = T_LBC - (q_flux / k_left) * x_grid(x_grid <= x_split);
T_exact(x_grid > x_split) = T_int - (q_flux / k_right) * (x_grid(x_grid > x_split)
- x_split);
%% ====== Visualization ======
figure('Color','w','Position',[120 120 900 450]);
% Pick times to plot
snapshots = [1, 80, 400, 2000, time_steps];
styles = {'-','--','-.',':','-'};
hold on;
for s = 1:length(snapshots)
plot(x_grid, Temp(:, snapshots(s)), styles{s}, 'LineWidth', 1.4, ...
'DisplayName', sprintf('t = %d', snapshots(s)));
end
% Analytic line
plot(x_grid, T_exact, 'k', 'LineWidth', 2, 'DisplayName', 'Analytic');
% Interface marker
yl = ylim;
plot([x_split x_split], yl, ':', 'Color', [0.3 0.3 0.3]);
xlabel('Position (x)');
ylabel('Temperature (°C)');
title('1D Steady Heat Conduction with Interface');
legend('Location', 'northeast');
grid on;
2
xlim([0 x_length]);
%% ====== Error Report ======
err_inf = max(abs(Temp(:, end) - T_exact'));
fprintf('Max absolute error at final time: %.6f\n', err_inf);
Max absolute error at final time: 49.064707