Euler.m
. Put this file in the same directory
you use for your other m-files
(additional help).
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
y1' = -2 y1 + y2 + t , | y1(1) = -1 |
y2' = y1 - 3 y2 , | y2(1) = 2 |
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')
For the IVP
y'' + y' - 2y = t, y(0)=1, y'(0)=-2find 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)