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--')

posted @ 2015-03-28 07:40  vigorpush  阅读(355)  评论(0编辑  收藏  举报