Solving an initial value problem with ode45

Contents

You need to download an m-file

You have to download the m-file dirfield.m.

format short g

Initial value problem

We consider the initial value problem

$$y'=y-t,\qquad y(-2)=-1.2$$

and we want to find the solution y(t) for t in [-2,1].

f = @(t,y) y-t;                   % define function f(t,y)
dirfield(f,-2:.2:1, -2:.2:0.2); hold on
xlabel('t'); ylabel('y')
title('Direction field and initial point')

t0 = -2;  y0 = -1.2;              % initial point
plot(t0,y0,'bo')

Solve IVP with ode45

ode45 returns a vector ts of t values and a vector ys of corresponding y values.

Note that the last entry ys(end) is the y-value for time T. We can plot the solution $y(t)$ using plot(ts,ys).

T = 1;                            % final t-value
[ts,ys] = ode45(f,[t0,T],y0);     % solve IVP

yfinal = ys(end);                 % value for y at time T
fprintf('y(T) = %g\n',yfinal)

disp('       t           y')
disp([ts,ys])                     % table of t and y values of solution

plot(ts,ys,'b')                   % plot solution
title('Solution of IVP')
y(T) = -2.01711
       t           y
           -2         -1.2
       -1.925      -1.1406
        -1.85      -1.0824
       -1.775      -1.0255
         -1.7     -0.96997
       -1.625       -0.916
        -1.55     -0.86366
       -1.475     -0.81309
         -1.4     -0.76442
       -1.325     -0.71781
        -1.25      -0.6734
       -1.175     -0.63138
         -1.1     -0.59192
       -1.025     -0.55523
        -0.95     -0.52153
       -0.875     -0.49104
         -0.8     -0.46402
       -0.725     -0.44074
        -0.65     -0.42149
       -0.575     -0.40657
         -0.5     -0.39634
       -0.425     -0.39115
        -0.35      -0.3914
       -0.275     -0.39751
         -0.2     -0.40993
       -0.125     -0.42917
        -0.05     -0.45574
        0.025     -0.49022
          0.1     -0.53324
        0.175     -0.58544
         0.25     -0.64755
        0.325     -0.72034
          0.4     -0.80464
        0.475     -0.90135
         0.55      -1.0114
        0.625      -1.1359
          0.7      -1.2759
        0.775      -1.4327
         0.85      -1.6076
        0.925      -1.8019
            1      -2.0171