solve this heat conduction equation pde in matlab using implicit euler for time and central differencing for space in matlab. use a jacobi solver in matlab

We can solve the heat conduction equation using implicit Euler for time and central differencing for space with Jacobi iteration as follows:

main.m
% Define parameters
L = 1; % length of domain
N = 101; % number of grid points
dx = L/(N-1); % spatial step size
x = linspace(0, L, N)'; % spatial grid
T = 1; % total time to solve for
dt = 0.01; % temporal step size
Nt = ceil(T/dt); % number of time steps
alpha = 0.1; % thermal diffusivity coefficient
r = alpha*dt/dx^2; % stability parameter
T_init = sin(pi*x); % initial temperature profile

% Initialize temperature matrix
Tn = T_init;
Tnm1 = T_init;

% Set up coefficient matrix and RHS vector
A = diag(1+2*r*ones(N-2, 1)) + diag(-r*ones(N-3, 1), 1) + diag(-r*ones(N-3, 1), -1);
A = sparse(A);
b = zeros(N-2, 1);

% Jacobi iteration
for n = 1:Nt
    % Compute RHS vector
    b(1) = r*Tnm1(1);
    b(N-2) = r*Tnm1(N);
    b(2:N-3) = Tnm1(2:N-3) + r*(Tnm1(1:N-4) - 2*Tnm1(2:N-3) + Tnm1(3:N-2));
    
    % Solve system
    Tn(2:N-1) = jacobi(A, b, Tnm1(2:N-1));
    
    % Update time step
    Tnm1 = Tn;
end

% Plot final temperature profile
plot(x, Tn);
xlabel('x');
ylabel('T');
title('Temperature Profile at t=T');
1023 chars
41 lines

The jacobi function used above is a custom function that performs the Jacobi iteration. Its code is given below:

main.m
function [x_new] = jacobi(A, b, x_old)
% Performs one iteration of Jacobi method
x_new = (b - A*x_old)./diag(A);
end
117 chars
5 lines

Note that we only need to solve for the interior grid points, so the first and last entries in the Tn and b vectors are skipped.

Also note that the forward Euler method is conditionally stable, meaning that the timestep size must be chosen carefully based on the spatial step size and diffusion coefficient to ensure stability. The Jacobi iteration is used to solve the resulting linear system at each timestep.

related categories

gistlibby LogSnag