%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Forward Euler method
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for MTH 452-552
%%% this is a simple example how to set up 
%%% a one-step explicit method (here Euler method is used)
%%% to solve a scalar IVP
%%% the data for the problem <f,y0,T,n> can be modified
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
%% M. Peszynska,  2005/1
%% Copyright Department of Mathematics, Oregon State University
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
%%% INSTRUCTIONS: the code can be executed as script or retyped
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
%% set up the function
f = inline('-y','t','y');
%% fix the initial condition
y0 = 1; 
%% set up the time interval and its discretization
T = 10; 
n = 20; 
h = T/n; 
%% time steps are stored in t
t = 0:h:T; 
%% the numerical solution will be in yh
yh = zeros(n+1,1);
%% initial condition
yh(1) = y0;
for i=1:n yh(i+1) = yh(i) + h * f( t(i), yh(i) ); end;
%% plot the analytical and numerical solution 
plot(t,exp(-t),'k',t,yh,'r');
pause
%% plot the analytical solution and then plot individual steps of numerical
%% solution
plot(t,exp(-t),'k'); hold on;
for i=1:n 
    plot([t(i),t(i+1)],[yh(i),yh(i+1)],'r*');pause,
end;
hold off;
