Using the Euler method in Matlab

You first need to download the m-file Euler.m. Put this file in the same directory you use for your other m-files (additional help).

Example for one ODE:

y' = -y + t, y(0)=1, find y(t) for t between 0 and 2 using 20 steps of Euler method: Using inline function:
f1 = inline('-y + t','t','y')
[ts,ys] = Euler(f1,[0,2],1,20);     
[ts,ys]                             %  table of t and y-values
plot(ts,ys,'o-')
Show direction field and approximations with N=5,10,20 together:
dirfield(f1,[0:.1:2.5],[.4:.1:1.5]); hold on
for N = [5,10,20]
  [ts,ys] = Euler(f1,[0,2],1,N);
  plot(ts,ys,'o-')
end
hold off

Example for system of ODEs:

y1' = -2 y1 + y2 + t ,         y1(1) = -1
y2' = y1 - 3 y2 ,         y2(1) = 2
Find y1(t),y2(t) for t between 1 and 3 using 20 steps of Euler method:
f = inline('[ -2*y(1) + y(2) + t; y(1) - 3*y(2) ]', 't','y')
[ts,ys] = Euler(f, [1,3], [-1;2], 20);
[ts,ys]              %  show table with columns for t, y1, y2 
plot(ts,ys,'o-')     %  plot solutions y1, y2 
legend('y1','y2')  

Example for 2nd order ODE:

For the IVP

y'' + y' - 2y = t,     y(0)=1, y'(0)=-2
find y(t) for t between 0 and 1, using 20 steps of the Euler method.

Rewrite as a first order system with y1=y and y2=y': We then have y1' = y2 and y2' = y'' = t - y' + 2y = t - y2 + 2y1. So the system is
y1' = y2 ,         y1(0) = 1
y2' = t - y2 + 2y1 ,         y2(0) = -2

Now define the function f. Then we use the Euler method for t between 0 and 1 using 20 steps:

f = inline('[ y(2) ; t - y(2) + 2*y(1) ]', 't','y')
[ts,ys] = Euler(f, [0,1], [1;-2], 20);
[ts,ys]                   %  show table with columns for t, y, y' 
plot(ts,ys(:,1),'o-')     %  plot solution y (1st column of ys)