Heun's method stiff ODE
Show older comments
% solving the equation analyticaly
clear all
clc
s = dsolve('Dx = -2.3*x','x(0) = 1', 't');
sol = simplify(s)
% plot the analytical solution in the time interval
t0 = 0;
h = 0.01;
tend = 5;
t = [t0:h:tend];
sol = exp(-(2.3*t));
plot (t, sol, 'k-')
hold on;
% solving the equation numerically using explicit Euler's method
x0 = 1;
h1 = 1;
N = (tend - t0)/h1;
t = [t0:h1:tend];
x(1) = x0;
for i = 1:N
x(i+1) = x(i)+0.5*(h1*-2.3*x(i)+h1*-2.3*(h1*-2.3*x(i)));
end
plot(t,x,'o--')
title('Figure 3.5: Stiff ODE with Euler method when h = 1')
legend({'exact', 'Euler'},'location','southeast')
xlabel('t')
ylabel('x')
ax = gca;
ax.XTick = 0:1:5;
ax.XAxisLocation = 'origin';
ax.YAxisLocation = 'origin';
box off;
hold off;
Is there something wrong with my code??
As the correct graph is not showing.
3 Comments
John D'Errico
on 11 Jun 2021
What did result? Do you recognize that since the problem is stiff, and that an explicit Euler method is often NOT expected to produce a viable result on stiff problems. That is why you are learning about stiff problems.
Jan
on 11 Jun 2021
As far as I see, this comment is missleading:
% solving the equation numerically using explicit Euler's method
Paul
on 11 Jun 2021
Is there a reference for the equation
x(i+1) = ...
Also, what makes this first order differential equation with exponential solution stiff?
Accepted Answer
More Answers (1)
Sulaymon Eshkabilov
on 12 Jun 2021
There are a few crucial errs in your code. Here is the completely corrected code. Note that the step size of h1 = 1 gives very crude numerical soutions and thus, h1 has to be chosen carefully.
clearvars; clc % It is better start with clearvars instead of clear all that takes some time
syms x(t) % This one is recommended syntax of Symbolic Math toolbox
Dx = diff(x, t); % This one is recommended syntax
s = dsolve(Dx == -2.3*x,x(0) == 1); % This one is recommended syntax
sol = simplify(s)
% plot the analytical solution in the time interval
t0 = 0;
h = 0.01; % This is a reasonably small step size
tend = 5;
t = t0:h:tend;
sol = subs(sol, t); % Use the above computed symbolic solution
plot(t, sol, 'k-')
hold on
% solving the equation numerically using explicit Euler's method
x0 = 1;
h1 = 0.25; % Step size needs to be selected carefully
t = t0:h1:tend;
y = [x0, zeros(1, numel(t)-1)]; % Memory allocation
for i = 1:numel(t)-1
y(i+1) = y(i)+0.5*h1*(-2.3*y(i)+y(i)+-2.3*h1*y(i)); % See the corrected loop
end
plot(t,y,'o--')
title('Figure 3.5: Stiff ODE with Euler method when h = 1')
legend({'exact', 'Euler'},'location','southeast')
xlabel('t')
ylabel('x')
ax = gca;
ax.XTick = 0:1:5;
ax.XAxisLocation = 'origin';
ax.YAxisLocation = 'origin';
box off;
hold off;
Categories
Find more on Programming in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!