Info

Questa domanda è chiusa. Riaprila per modificarla o per rispondere.

solving heat equation using explicit method

1 visualizzazione (ultimi 30 giorni)
Erm
Erm il 5 Set 2024
Chiuso: John D'Errico il 5 Set 2024
I need a help for the following code to locate the error since the numerical solution is not approximate the exact one. The heat equation have 0 boundary conditions
clear all;
clc;
L = 2; % Length of the wire
T =1; % Final time
% Parameters needed to solve the equation within the explicit method
maxk = 210; % Number of time steps
dt = T/maxk;
n = 10; % Number of space steps
dx = L/n;
a = 1;
r= a*dt/(dx*dx); % b should be less than 0.5
% Initial temperature of the wire: a sinus.
for i = 1:n+1
x(i) =(i-1)*dx;
u(i,1) =sin((pi/2)*x(i));
end
% boundary
for t=1:maxk+1
time(t) = (t-1)*dt;
u(1,t) = 0;
u(n+1,t) = 0;
end
% Implementation of the explicit method
for t=1:maxk % Time Loop
for i=2:n; % Space Loop
u(i,t+1) =u(i,t) + r*(u(i-1,t)+u(i+1,t)-2.*u(i,t)) + dt*(x(i)-time(t));
end
end
%Exact= @(x, t) exp(-(pi^2/4)*t) .* sin((pi/2) * x);
%f = Exact(x, t);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%55
% Parameters
LL = 2; % Length of the domain (0 to 2)
xx = linspace(0, LL, 100); % Discretize the x domain (0 to 2)
t_values = [0, 0.05, 0.1]; % Time values to plot
% Define the function u(x,t)
u_exact = @(xx, tt) exp(-pi^2/4 * tt) .* sin(pi/2 * xx);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Graphical representation of the temperature at different selected times
figure(1)
plot(x,u(:,1),'-',x,u(:,10),'-',x,u(:,45),'-',x,u(:,30),'-',x,u(:,60),'-')
title('numerical')
xlabel('X')
ylabel('T')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5
figure(2);
hold on;
for tt = t_values
uu = u_exact(xx, tt);
plot(xx, uu, 'DisplayName', ['t = ', num2str(tt)]);
end
% Labels and legend
xlabel('x');
ylabel('u(x,t)');
title('Exact solution ');
legend show;
grid on;
hold of
  4 Commenti
John D'Errico
John D'Errico il 5 Set 2024
You already asked this question at least once. You got answers.
Torsten
Torsten il 5 Set 2024
If you plot the exact solution at the correct times, namely
t_values = [0, 9*dt, 29*dt,44*dt,59*dt]; % Time values to plot
you will see that exact and numerical solution agree.

Risposte (0)

Questa domanda è chiusa.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by