Matlab forward Euler demo

时间:2023-03-09 10:01:46
Matlab forward Euler demo
% forward Euler demo
% take two steps in the solution of
% dy/dt = y, y(0) = 1
% exact solution is y(t) = exp(t) clear all
close all % the exact solution
t = 0:0.01:1;
yexact = exp(t); % initial conditions
y0 = 1
h = 0.5
tt = [0];
yy = [y0]; % one step of forward Euler
yhalf = y0 +h*y0
tt = [tt; h];
yy = [yy; yhalf]; plot(t,yexact)
axis([0,1,0,3])
hold on
plot(tt,yy,'rx-')
pause
% what family member are we on now?
c1 = yhalf/exp(0.5);
ymember1 = c1*exp(t);
plot(t,ymember1,'g--')
pause % step 2 of forward Euler
y1 = yhalf + h*yhalf
tt = [tt; 2*h];
yy = [yy; y1]; plot(tt,yy,'rx-')
pause
% what family member are we on now?
c2 = y1/exp(1);
ymember2 = c2*exp(t);
plot(t,ymember2,'c--')