MATH 267 How to Solve ODEs in MATLAB

advertisement
MATH 267
How to Solve ODEs in MATLAB
MATLAB contain very easy to use commands for solving initial value problems
for ordinary differential equations. Suppose we wish to obtain a numerical solution
of
y 0 = f (t, y)
y(t0 ) = y0
This can be done with the following command:
>>[t,y] = ode45(f,tspan,y0)
where the inputs f,tspan,y0 and outputs t,y are as follows.
f: defines the function in the ODE. For example to get f (t, y) = t2 − y 3 , give the
MATLAB command1
>>f=inline(’t∧2-y∧3’,’t’,’y’)
tspan: defines the endpoints of the interval on which you want the solution, e.g.
>> tspan=[1 3]
to get the solution for 1 ≤ t ≤ 3. The first entry should be t0 .
y0: the initial value, e.g, for y0 = 4 give the MATLAB command
>> y0=4
t: a vector of t values t1 , t2 . . . tn at which the approximate solution is given.
y: a vector of y values y1 , y2 . . . yn where yj is the approximate solution at tj .
The command
>>plot(t,y)
tells MATLAB to plot the solution. The command
>>print -dps figure
produces the postscript file figure.ps of the plot which you can print.
HOMEWORK
1. Use the above procedure to numerically solve
y 0 = t2 − y 3
y(1) = 4
on the interval 1 ≤ t ≤ 3 and plot the result. (You should not print out a listing of
all of the yn values!)
2. Numerically solve
y0 = y + t
y(0) = 1
on the interval 0 ≤ t ≤ 1 and plot the result. Compare the numerical solution to
1
the exact solution at t = and t = 1.
2
3. Do #4 on page 311.
1
Alternatively, you may define f by means of an m-file, see page 48 of the MATLAB text, in
which case the calling command should be >>[t,y] = ode45(’f’,tspan,y0)
Download