ans =
Numerical solution for the heat equation does not match the exact solution
이전 댓글 표시
I write a matlab code for the problem, and i want to compare the numerucal and the exact solution at t=0.5 but the graph of the soultions are very different.
The problem is in the following:



% Parameters
L = 5; % Length of the rod
T = 1; % Total time
Nx = 100; % Number of spatial points
Nt = 500; % Number of time steps
alpha = 0.01; % Thermal diffusivity
% Discretization
dx = 0.1; % Spatial step size
dt = 0.04; % Time step size
r = alpha * dt / dx^2; % Stability parameter for the scheme
% Initial condition
x = linspace(0, L, Nx);% generates Nx points. The spacing between the points is (L-0)/(Nx-1).
u = cos(x-0.5); % initial condition
% Preallocate solution matrix
U = zeros(Nx, Nt+1); % returns an Nx-by-Nt matrix of zeros
U(:,1) = u; %extracts all the elements from the first column of matrix
% Time-stepping loop
for n = 1:Nt
% Update the solution using explicit scheme for the Heat Equation
for i = 2:Nx-1
U(i,n+1) = U(i,n) + r * (U(i+1,n) - 2*U(i,n) + U(i-1,n));
end
end
Numerical_sol = U
% Plot results
t = linspace(0, T, Nt+1);
[X, T] = meshgrid(x, t);
% Exact solution
Exact= @(x, t) exp(-t) .* cos(pi * x - 0.5 * pi);
figure;
mesh(X, T, U');
xlabel('x');
ylabel('t');
zlabel('u(x,t)');
title('Heat Equation Solution');
figure
plot(x, U(:,1), 'o');
댓글 수: 2
John D'Errico
2024년 9월 5일
You accepted the answer to this question. Then you asked it just again, 42 minutes ago. I closed the duplicate question, since it asks nothing you should not have learned here.
Torsten
2024년 9월 5일
I didn't know that you are the Website Master taking the right to delete questions and answers that are actually in flow.
채택된 답변
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

