Professional Documents
Culture Documents
Laboratory Manual
with SIMULINK
examples
Bruno D. Welfert
to accompany
Fundamentals of
Differential Equations
Sixth Edition
and
Fundamentals of
Differential Equations
and
Boundary Value Problems
Fourth Edition
Nagle Sa Snider
i
MATLAB
and SIMULINK
k=1
1
k
2
=
2
6
.
Can k and incr be both initialized by 0?
3. if statement: evaluate y =
1
x2
for a given (but unknown) scalar x
function y=f(x)
if x==2
disp(y is undefined at x = 2)
else
y=1/(x-2);
end
Introduction to MATLAB 17
or with switch statement:
function y=f(x)
switch x
case 2
disp(y is undefined at x = 2)
otherwise
y=1/(x-2);
end
Try f(1), f(2). Modify the example to allow for arrays as input.
Whenever possible all these construct should be avoided and available MATLAB functions used to
improve eciency. In particular lengthy do loops introduce a substantial overhead. Compare
>> tic; S=0; for k=1:1000000; S=S+1/k^2; end; toc; S
elapsed_time =
1.8830
S =
1.6449
and
>> tic; S=sum(1./(1:1000000).^2); toc; S
elapsed_time =
0.0800
S =
1.6449
Programming with MATLAB is fairly easy. Still a script or function may not execute properly due
to some programming error. In this case MATLAB returns an error indicating where it stopped and
why. Most of the time this is sucient to nd out the error and correct it, especially when you get used
to it. But keep in mind that even non-fatal mistakes may eventually force a program to later crash.
Debugging tools are available in the MATLAB editor to force the execution to stop at specic places
within a script or function(s) and access the current state of available variables.
Write a script or function with the MATLAB editor and position the cursor on a selected line. Then
try the buttons and in the editor window before executing the le in the Command Window.
Observe what happens. Check the value of variables. To continue and eventually exit the debugger press
return.
Exercises
Now that you have been through the essential elements of MATLAB relevant in this text, a good exercise
is to go through the commands and change values, functions, and problems to familiarize yourself with
the MATLAB syntax and commands introduced in this chapter.
18 Introduction to MATLAB
Chapter 2
Ordinary Dierential Equations
with MATLAB
In this chapter we demonstrate the use of MATLAB in working with ordinary dierential equations
(ODE) and initial value problems (IVP) of the form
_
y
= f(t, y),
y(t
0
) = y
0
.
In particular, we discuss the following topics:
1. Numerical dierentiation and solution of the IVP.
2. Direction elds and graphical solution (1.3 and 5.4 of the Nagle/Sa/Snider text).
3. Numerical solution of rst-order scalar IVPs using standard MATLAB routines (3.6 and 5.3 of
the Nagle/Sa/Snider text).
4. Systems of ordinary dierential equations (5.2, 5.4, and 5.5 of the Nagle/Sa/Snider text).
Numerical Dierentiation and Solution of the IVP
Consider the linear ODE y
= t
2
y. To (numerically) verify that y(t) = t
2
2t +2 +Ce
t
is a solution
for any constant C for t [3, 3] we pick C at random and compare both sides of the ODE with y = y(t)
for a large number of t-values:
>> C=randn % random value using normal distribution
C =
-1.4060
>> h=.1; t=-3:h:3; % 61 values in [-3,3]. Same as t=linspace(-3,3,61)
>> y=t.^2-2*t+2+C*exp(-t); % evaluate y(t)
>> dy=diff(y); dt=diff(t); % difference between consecutive ys and ts
>> rhs=t.^2-y; % evaluate rhs of ODE
>> lhs=dy./dt; % evaluate lhs of ODE
>> axis equal; axis([-4 4 -4 4]); grid on; % adjust look...
>> plot(t(2:end),lhs,r,t,rhs,b) % plot lhs, rhs (adjust size of t for lhs)
Note that t is 1 61 while dy, dt, and lhs are 1 60 so that rhs must be plotted against t(2:end)
(=t(2:61)) rather than t. Fig. 2.1 shows both lhs ( y
and t
2
y
Direction Fields
(1.3, 5.4 of the Nagle/Sa/Snider text)
>> t=-3:.5:3; y=-3:.5:3; % define grid of values in t and y directions
>> [T,Y]=meshgrid(t,y); % creates 2d matrices
>> dT=ones(size(T)); % dt=1 for all points
>> dY=T.^2-Y; % dy=(t^2-y)*dt: this is the ODE
>> quiver(T,Y,dT,dY) % draw arrows (t,y) --> (t+dt,y+dy)
>> axis equal; axis([-4 4 -4 4]); grid on; % adjust look...
>> print -depsc dfielda.eps % export plot (color encapsulated PostScript)
Longer arrows indicate larger values of y
. When y
= t
2
y (left: constant dt, right: scaled dt).
22 Ordinary Dierential Equations with MATLAB
4 3 2 1 0 1 2 3 4
4
3
2
1
0
1
2
3
4
Figure 2.3: Direction eld for y
= t
2
y with particular solution.
The Graphical User Interface dfield6 from J. Polking (available at http://math.rice.edu/dfield)
can also be used to plot the direction eld and selected solution curves. ODEs with up to two parameters
can be entered in a setup window, see Figure 2.4. A sample display window is shown in Figure 2.5.
Ordinary Dierential Equations with MATLAB 23
Figure 2.4: The dfield6 setup GUI
Figure 2.5: The dfield6 direction eld plot
24 Ordinary Dierential Equations with MATLAB
First-Order Scalar IVP
(3.6, 5.3 of the Nagle/Sa/Snider text)
Consider the IVP
_
y
= t y,
y(0) = 1.
(2.1)
The exact solution is y(t) = t 1 +2e
t
. A numerical solution can be obtained using various MATLAB
solvers. The standard MATLAB ODE solver is ode45. Help on ode45 can be obtained by typing
>> help ode45
ODE45 Solve non-stiff differential equations, medium order method.
[T,Y] = ODE45(ODEFUN,TSPAN,Y0) with TSPAN = [T0 TFINAL] integrates the
system of differential equations y = f(t,y) from time T0 to TFINAL with
initial conditions Y0. Function ODEFUN(T,Y) must return a column vector
corresponding to f(t,y). Each row in the solution array Y corresponds to
a time returned in the column vector T. To obtain solutions at specific
times T0,T1,...,TFINAL (all increasing or all decreasing), use
TSPAN = [T0 T1 ... TFINAL].
[T,Y] = ODE45(ODEFUN,TSPAN,Y0,OPTIONS) solves as above with default
integration properties replaced by values in OPTIONS, an argument created
with the ODESET function. See ODESET for details. Commonly used options
are scalar relative error tolerance RelTol (1e-3 by default) and vector
of absolute error tolerances AbsTol (all components 1e-6 by default).
[T,Y] = ODE45(ODEFUN,TSPAN,Y0,OPTIONS,P1,P2...) passes the additional
parameters P1,P2,... to the ODE function as ODEFUN(T,Y,P1,P2...), and to
all functions specified in OPTIONS. Use OPTIONS = [] as a place holder if
no options are set.
...
Example
[t,y]=ode45(@vdp1,[0 20],[2 0]);
plot(t,y(:,1));
solves the system y = vdp1(t,y), using the default relative error
tolerance 1e-3 and the default absolute tolerance of 1e-6 for each
component, and plots the first component of the solution.
See also
other ODE solvers: ODE23, ODE113, ODE15S, ODE23S, ODE23T, ODE23TB
options handling: ODESET, ODEGET
output functions: ODEPLOT, ODEPHAS2, ODEPHAS3, ODEPRINT
ODE examples: RIGIDODE, BALLODE, ORBITODE
...
Comments on advanced features have been omitted.
Basic ode45 Usage
The basic usage of ode45 requires a function ODEFUN, a time interval on which to solve the IVP, and
an initial condition. For scalar rst-order ODEs the function may often be specied using the inline
MATLAB command. A complete MATLAB solution would read:
Ordinary Dierential Equations with MATLAB 25
1 f = inline(t-y,t,y);
2 [t,y] = ode45(f,[0,3],1);
3 plot(t,y)
(line numbers are not part of the commands!) Line 1 denes the function f as a function of t and y, i.e.,
f(t, y) = t y. This is the right-hand side of the ODE (2.1). Line 2 solves the IVP numerically using
the ode45 solver. The rst argument is the function f, the second one determines the time interval on
which to solve the IVP in the form [initial time, nal time], and the last one species the initial value
of y. The output of ode45 consists of two arrays: an array t of discrete times at which the solution has
been approximated, and an array y with the corresponding values of y. These values can be listed in
the Command Window as
[t,y]
ans =
0 1.0000
0.0502 0.9522
0.1005 0.9093
0.1507 0.8709
0.2010 0.8369
0.2760 0.7936
0.3510 0.7590
0.4260 0.7322
0.5010 0.7129
0.5760 0.7003
0.6510 0.6940
0.7260 0.6937
0.8010 0.6988
0.8760 0.7089
0.9510 0.7237
1.0260 0.7429
1.1010 0.7661
1.1760 0.7930
1.2510 0.8234
1.3260 0.8571
1.4010 0.8937
1.4760 0.9331
1.5510 0.9750
1.6260 1.0194
1.7010 1.0660
1.7760 1.1146
1.8510 1.1651
1.9260 1.2174
2.0010 1.2714
2.0760 1.3268
2.1510 1.3837
2.2260 1.4419
2.3010 1.5013
2.3760 1.5618
2.4510 1.6234
2.5260 1.6859
2.6010 1.7494
2.6760 1.8136
2.7510 1.8787
2.8260 1.9445
2.9010 2.0109
26 Ordinary Dierential Equations with MATLAB
2.9257 2.0330
2.9505 2.0551
2.9752 2.0773
3.0000 2.0996
For example the approximate solution at t 1.0260 is y 0.7429. Unless specic values of y are needed
it is better in practice to simply plot the solution to get a sense of the behavior of the solution. Line
3 thus plots y as a function of t in a gure window. The plot, shown in Figure 2.6, can be saved or
exported in various formats using the File menu of the gure window.
0 0.5 1 1.5 2 2.5 3
0.6
0.8
1
1.2
1.4
1.6
1.8
2
2.2
Figure 2.6: Solution of (2.1).
Error Plot, Improving the Accuracy
Error plots are commonly used to estimate the accuracy in the numerical solution. Here the error is
the dierence between the exact solution y(t) = t 1 +2e
t
and the numerical approximation obtained
from ode45. Since this approximation is only given at specied time values (contained in the array t)
we only evaluate this error at these values of t:
err = t-1+2*exp(-t)-y
err =
1.0e-005 *
0
0.0278
0.0407
0.0162
-0.0042
0.1772
0.2638
0.0989
-0.0431
0.0942
Ordinary Dierential Equations with MATLAB 27
0.1610
0.0414
-0.0615
0.0423
0.0938
0.0070
-0.0675
0.0110
0.0506
-0.0123
-0.0663
-0.0069
0.0235
-0.0221
-0.0611
-0.0163
0.0070
-0.0260
-0.0542
-0.0204
-0.0025
-0.0264
-0.0468
-0.0212
-0.0075
-0.0248
-0.0395
-0.0203
-0.0098
-0.0223
-0.0329
-0.0321
-0.0313
-0.0305
-0.0298
Again, a plot of err versus t is more revealing. To do this note that errors are usually small so it is
best to use a logarithmic scale in the direction corresponding to err in the plot. To avoid problems with
negative numbers we plot the absolute value of the error (values equal to 0, e.g. at the initial time, are
not plotted):
semilogy(t,abs(err)); grid on;
See Figure 2.7. Note that the error level is about 10
6
. It is sometimes important to reset the default
accuracy ode45 uses to determine the approximation. To do this use the MATLAB odeset command
prior to calling ode45, and include the result in the list of arguments of ode45:
1 f = inline(t-y,t,y);
2 options = odeset(RelTol,1e-10,AbsTol,1e-10);
3 [t,y] = ode45(f,[0,3],1,options);
4 err = t-1+2*exp(-t)-y;
5 semilogy(t,abs(err))
See Figure 2.8.
28 Ordinary Dierential Equations with MATLAB
0 0.5 1 1.5 2 2.5 3
10
8
10
7
10
6
10
5
Figure 2.7: Error in the solution of (2.1) computed by ode45.
0 0.5 1 1.5 2 2.5 3
10
16
10
15
10
14
10
13
10
12
10
11
10
10
Figure 2.8: Error in the solution of (2.1) computed by ode45 with a better accuracy.
Ordinary Dierential Equations with MATLAB 29
Integration
For initial value problems of the form
y
= f(t), y(t
0
) = y
0
, (2.2)
the solution can be explicitly obtained as
y(t) = y
0
+
_
t
t
0
f(u)du. (2.3)
To obtain a numerical approximation of y at some t ,= t
0
one can use ode45 and solve the IVP, or use
an integration routine such as quadl. For f(t) = sin t and y(0) = 1, the value y() is computed as
follows.
>> f = inline(sin(t),t); % one variable
>> tf = pi/2; format long;
>> yf = -1+quadl(f,0,tf) % formula (2.3)
yf =
0.99999997747113
>> f = inline(sin(t),t,y); % two variables
>> [t,y] = ode45(f,[0,tf],-1);
>> yf = y(end) % computed by solving (2.2)
yf =
0.99999999832175
The exact answer is of course yf = 1. Note that quadl requires a function of one variable while ode45
requires a function of two variables (even if y does not explicitly appear in the right-hand side of the
ODE). The accuracy of the approximation can also be increased in quadl, type help quadl for more
information.
Parameter-Dependent ODE
When the ODE depends on a parameter the inline command cannot be used. Instead the ODE right-
hand side in entered as a separate function le, included in the same le as the calling sequence of
ode45 (as below) or saved in a separate m-le (see page 10). Consider for example the IVP
_
y
= a (y e
t
) e
t
,
y(0) = 1.
(2.4)
with exact solution y(t) = e
t
(independent of the parameter a!). An implementation of the MATLAB
solution follows.
1 function ex_with_param
2 t0 = 0; tf = 3; y0 = 1;
3 a = 1;
4 [t,y] = ode45(@f,[t0,tf],y0,[],a);
5 disp([y( num2str(t(end)) ) = num2str(y(end))])
6 disp([length of y = num2str(length(y))])
7 %-------------------------------------------------
8 function dydt = f(t,y,a)
9 dydt = -a*(y-exp(-t))-exp(-t);
Line 1 must start with function, since the le contains at least two functions (a driver + a function).
Line 2 sets the initial data and the nal time. Line 3 sets a particular value for the parameter a. In line
4 the parameter is passed to ode45 as the 5
th
argument (the 4
th
argument is reserved for setting options
such as the accuracy using odeset, see page 27, and the placeholder [] must be used if default options
30 Ordinary Dierential Equations with MATLAB
are used). Correspondingly the function f dened lines 8-9 must include a 3
rd
argument corresponding
to the value of the parameter. See the help on ode45 for more information. On line 5 the value of y(1)
as computed by ode45 is then displayed in a somewhat fancier form than the one obtained by simply
entering y(end).
The m-le ex with param.m is executed by entering ex with param at the MATLAB prompt. The
output is
>> ex_with_param
y(3) = 0.049787
length of y = 45
The additional line 6 in the le lists the length of the array y computed by ode45. It is interesting
to check the size of y obtained for larger values of a. For example for a = 1000 we obtain
>> ex_with_param
y(3) = 0.049792
length of y = 3621
This means that ode45 needed to take smaller step sizes to cover the same time interval compared to
the case a = 1, even though the exact solution is the same!
Not all problems with a common solution are the same! Some are easier to solve than others.
When a is large the ODE in (2.4) is said to be sti. Stiness has to do with how fast nearby solutions
approach the solution of (2.4), see Figure 2.9.
0 0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.1
0.9
0.91
0.92
0.93
0.94
0.95
0.96
0.97
0.98
0.99
1
t
y
y = a (y exp( t)) exp( t) a = 1
0 0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.1
0.9
0.91
0.92
0.93
0.94
0.95
0.96
0.97
0.98
0.99
1
t
y
y = a (y exp( t)) exp( t) a = 1000
Figure 2.9: Direction eld and sample solutions in the t-y window [0, 0.1] [0.9, 1] as obtained using
DFIELD6: a = 1 (left) and a = 1000 (right).
Other MATLAB ODE solvers are designed to better handle sti problems. For example replace ode45
with ode15s in ex with param.m (without changing anything else) and set a = 1000:
4 [t,y] = ode15s(@f,[t0,tf],y0,[],a);
>> ex_with_param
y(3) = 0.049787
length of y = 18
Ordinary Dierential Equations with MATLAB 31
Higher-Order and Systems of IVPs
(5.2, 5.4, 5.5 of the Nagle/Sa/Snider text)
We show here how to extend the use of ode45 to systems of rst-order ODEs (the same holds for other
solvers such as ode15s). Higher-order ODEs can rst be transformed into a system of rst-order ODEs
to t into this framework. See Lab 7 page 72 to nd out how to do this.
As an example consider the system (Lotka-Volterra) representing the evolution of two populations
u
1
= u
1
(t) and u
2
= u
2
(t):
_
_
du
1
dt
= au
1
bu
1
u
2
,
du
2
dt
= cu
2
+du
1
u
2
(2.5)
with initial populations u
1
(0) = 10 and u
2
(0) = 60. The parameters a, b, c, and d are set to a = 0.8,
b = 0.01, c = 0.6, and d = 0.1. The particular signicance of these parameters is discussed in Lab 11
page 94. The time unit also depends on the type of populations considered.
Although the ODE problem is now dened with two equations, the MATLAB implementation is
very similar to the case of a single ODE, except that vectors must now be used to describe the unknown
functions.
1 function ex_with_2eqs
2 t0 = 0; tf = 20; y0 = [10;60];
3 a = .8; b = .01; c = .6; d = .1;
4 [t,y] = ode45(@f,[t0,tf],y0,[],a,b,c,d);
5 u1 = y(:,1); u2 = y(:,2);
6 figure(1);
7 subplot(4,1,1); plot(t,u1,b-+); ylabel(u_1)
8 subplot(4,1,2); plot(t,u2,r-o); ylabel(u_2)
9 subplot(2,1,2); plot(u1,u2); axis square; xlabel(u_1); ylabel(u_2);
10 %----------------------------------------------------------------------
11 function dydt = f(t,y,a,b,c,d)
12 u1 = y(1); u2 = y(2);
13 dydt = [ a*u1-b*u1*u2 ; -c*u2+d*u1*u2 ];
In line 2 the 2 1 vector y0 denes the initial condition for both u
1
and u
2
. In line 4 the parameters
are passed to the ODE solver ode45 as extra arguments (starting from the 5
th
), as many as there are
parameters in the problem (4 here). The output array y of ode45 now has 2 columns, corresponding to
approximations for u
1
and u
2
, respectively, instead of a single one. In line 5 these quantities are therefore
retrieved and stored in arrays u1 and u2, which are descriptive names. The part of the program dening
the ODE system includes lines 11-13. Note that all the parameters appearing as arguments of ode45
must appear as arguments of the function f. For a specic value of t the input y to f is a 2 1 vector,
whose coecients are the values of u
1
and u
2
at time t. Rather than referring to y(1) and y(2) in the
denition of the equations on line 13, it is best again to use variable names which are easier to identify,
e.g., u1 and u2. Line 13 denes the right-hand sides of the ODE system as a 2 1 vector: the rst
coecient is the rst right-hand side (
du
1
dt
) and the second coecient the second right-hand side (
du
2
dt
).
Lines 6-10 correspond to the visualization of the results in a single gure. The subplot command
is used somewhat creatively here. The plot includes the time series of u
1
and u
2
, and a phase plot
representing the evolution of u
2
in terms of u
1
. Because the scales of u
1
and u
2
are dierent it is best
using two dierent graphs for u
1
and u
2
here. Note that u
1
and u
2
vary cyclically. The periodic evolution
of the two populations becomes clear from the closed curve u
2
vs. u
1
in the phase plot.
32 Ordinary Dierential Equations with MATLAB
0 5 10 15
40
60
80
100
120
140
u
1
u
2
0 2 4 6 8 10 12 14 16 18 20
0
5
10
15
u
1
0 2 4 6 8 10 12 14 16 18 20
0
50
100
150
u
2
Figure 2.10: Lotka-Volterra example.
The following diagram explains the logic behind the selection of the arguments of the subplot
command in the program ex with 2eqs.
subplot(4,1,1)
subplot(4,1,2)
subplot(2,1,2)
u
1
vs. t
u
2
vs. t
u
2
vs. u
1
E
A phase plot can be obtained without solving the ODE system (2.5). Divide corresponding sides of
(2.5) to get
du
2
du
1
=
cu
2
+du
1
u
2
au
1
bu
1
u
2
= f(u
1
, u
2
). (2.6)
Ordinary Dierential Equations with MATLAB 33
The phase plot of (2.5) is simply the direction eld of (2.6). Because the independent variable u
1
in
(2.6) can increase or decrease as a function of time it is better to use a line option rather than an
arrow option in the calling sequence of dirfield:
>> f=inline((-.6*u2+.1*u1.*u2)./(.8*u1-.01*u1.*u2),u1,u2)
f =
Inline function:
f(u1,u2) = (-.6*u2+.1*u1.*u2)./(.8*u1-.01*u1.*u2)
>> dirfield(f,[0,15,40,140],line);
0 5 10 15
40
50
60
70
80
90
100
110
120
130
140
Figure 2.11: Phase plane for the ODE (2.6) using dirfield.
The Graphical User Interface PPLANE6 from J. Polking (available at http://math.rice.edu/dfield)
can also be used to get an idea of what phase plots can be expected to look like, see Figure 2.12. A
sample display window is shown in Figure 2.13.
ODESOLVE GUI
We briey mention the MATLAB Graphical User Interface odesolve.m by J. C. Polking, Rice University.
This GUI allows the user to solve arbitrary systems of ODEs. However it requires the MATLAB Symbolic
Toolbox, which is not widely available on campuses. To some extent it also defeats the purpose of
learning some MATLAB programming. In this manual we preferred instead introducing the reader to
the SIMULINK package, which is a more helpful tool in the design of models and is extensively used in
industry. Laboratory 13 page 107 is dedicated to this package.
34 Ordinary Dierential Equations with MATLAB
Figure 2.12: The PPLANE6 setup GUI
Figure 2.13: The PPLANE6 phase plot with a sample solution curve
Chapter 3
MATLAB sessions
In the previous chapters we gave a general introduction to MATLAB and an introduction on using
MATLAB to solve dierential equations. In this chapter, we present 13 laboratory sessions for use in
an introductory class on dierential equations. The idea behind these labs is to coordinate the use of
MATLAB with class instruction in dierential equations.
The MATLAB sessions deal with many of the most important numerical aspects of solving dierential
equations as well as building and understanding ODE models. Many of the labs are connected with the
material presented in the text Fundamentals of Dierential Equations by Nagle, Sa and Snider and
other texts. Of course these labs are not exhaustive in covering all topics covered in these texts.
The idea of these laboratory sessions is to get the student to actively participate in the learning of
how dierential equations are solved numerically. Using MATLAB presents several advantages. The
student will
easily visualize the behavior of solutions by means of direction elds and phase planes;
be able to handle mathematically intractable problems and generate numerical solutions;
understand how parameter dependent problems are implemented and the role of these parameters
in the solution of dierential equations;
be able to examine what-if situations to discover properties of dierential equations;
solve dierent types of problems from various elds of Science and Engineering.
The computer laboratory exercises that follow each session (or each section in a session) require the
students to do some work and therefore take an active part in their learning of dierential equations.
Each lab presents explanatory background material and some solved problems, but each also includes
problems for them to do. These problems range from simple problems, where the student must simply
ll-in dots ... left in a MATLAB code, to more involved problems that require working out a complete
MATLAB code. Additionally, the students are asked to summarize the observations and conclusions
they obtained while doing the exercises.
The laboratories should be used with discretion depending on the class situation. Some laboratories
deal more with numerical or graphical techniques, others focus more on applications. There is much
more material here than can be used during a single semester course. Instructors may wish to use only
parts of some laboratories. Some laboratories are lengthier than others and some parts may need to be
omitted.
What follows is a brief synopsis of each laboratory session.
Laboratory 1: First-Order Dierential Equations, Graphical Analysis Using Direction
Fields
(1.3 in Nagle/Sa/Snider text)
In this laboratory the students are shown how to plot direction elds for rst-order dierential
35
36 MATLAB sessions
equations, which are examined from a graphical point of view. The rather straightforward labora-
tory requires students to make some observations about the behavior of solutions from the direction
eld.
Laboratory 2: Numerical solutions by Euler and Improved Euler methods (scalar eqs.)
(1.4 and 3.6 in Nagle/Sa/Snider text)
This lab briey explains Eulers and Improved Eulers methods. A computer implementation for
each method is given. Exercises are included to compare numerical solutions with the exact solution
(when available).
Laboratory 3: Solution Sensitivity
(1.2 & Ch. 2 of the Nagle/Sa/Snider text)
Students are shown how small changes in the initial condition may yield very dierent solutions
(conditioning). As an extreme situation they are shown how a problem can have multiple solutions
and how numerical techniques and solvers available in MATLAB handle these problems. Students
are also shown how to recognize pure integration and autonomous problems from the direction
eld, as well as understand how to obtain equilibrium solutions.
Laboratory 4: Picard Iteration
(Ch. 1, Project B, page 32 in the Nagle/Sa/Snider text)
This laboratory deals with Picards method for solving an IVP. The method is rst explained in
terms of exact calculations. The technique, which is perhaps more appropriately illustrated using
a symbolic manipulator (e.g., the MATLAB Symbolic Toolbox) can also be implemented at a
numerical level. An explanation of how this can be done is given in the lab. A number of exercises
is included for the students to exercise with the two implementations proposed in the laboratory
and evaluate the convergence properties of the method.
Laboratory 5: Applications of First-Order Dierential Equations
(Ch. 3 of the Nagle/Sa/Snider text)
This is the rst of two labs on applications of rst-order dierential equations. The idea is to
model real world phenomena by means of dierential equations. First, three standard models are
discussed for population growth - the exponential, logistic, and modied logistic (also known as
Nagumo) models. Direction elds are generated to study the behavior of solutions to dierential
equations modelling the growth. Other phenomena such as cooling modelled by Newtons law of
cooling, the spread of diseases, and a mixing problem, are discussed.
Laboratory 6: Further Applications of First-Order Dierential Equations
(Project B of Ch. 2/Ch. 3 of the Nagle/Sa/Snider text)
This is the second of two labs on applications of dierential equations. There are basically three
applications: the snowplow problem, an problem on aircraft guidance in a crosswind, and a ther-
mostat problem for the heating and cooling of a building. All these applications are taken from the
Nagle, Sa & Snider text. MATLAB can easily handle such problems with varying parameters.
Many pieces of code are supplied.
Laboratory 7: Implementing Higher-Order Dierential Equations
(Ch. 4, 6 of the Nagle/Sa/Snider text)
This laboratory begins the study of second- and higher-order dierential equations. The student is
taught rst how to reduce higher-order ODEs to sets of rst-order dierential equations and write
the result in system form, then how to use built-in MATLAB commands to indiscriminately solve
numerically both homogeneous and non-homogeneous problems. Eulers method is also applied to
the solution of the resulting system. Additional problems include nonlinear examples.
Laboratory 8: The Mass-Spring System
(4.1-4.3 and 4.8 of the Nagle/Sa/Snider text)
This laboratory focuses on the harmonic oscillation of a mass-spring system, rst without, then
with damping. The model is explained in terms of mechanical forces. Students are shown the
eect of damping on the long time behavior of the solution. A Graphical User Interface modelling
MATLAB sessions 37
the actual movement of the system is used to establish a better connection between the graphical
representation of the solution and the physical state of the system.
Laboratory 9: The Pendulum
(4.7 of the Nagle/Sa/Snider text)
This is another application of second-order dierential equations. The motion of a simple pendulum
is modelled by a nonlinear ODE. The origin of the ODE is clearly explained in terms to mechanical
forces. A comparison between the full nonlinear model on one hand, and a linearized model on the
other hand, establishes the limits of the linearized model. The eect of damping is also investigated.
The ideas of energy conservation and dissipation are introduced in the form of exercises.
Laboratory 10: Forced Equations and Resonance
(4.9 of the Nagle/Sa/Snider text)
In this laboratory we take a deeper look at second-order, non-homogeneous equations. We concen-
trate on equations that have a periodic forcing term, such as a mass-spring system under periodic
stimulus. We rst analyze the amplitude of the resulting oscillation that develops after a certain
time, and show how, in cases of low damping/friction, this amplitude may dramatically increase
when the forcing term and the free system come into resonance. The phenomenon of beats is also
explained.
Laboratory 11: Analytical and Graphical Analysis of Systems
(5.1, 5.2, 5.4 and 9.1-9.6 of the Nagle/Sa/Snider text)
The focus in this laboratory is on two-dimensional linear systems. Students are shown how to de-
termine eigenvalues and eigenvectors of a matrix, and how to use the information to determine the
solution of a linear homogeneous ODE system. Phase plots for various cases (distinct real eigen-
values, equal real eigenvalues, distinct complex conjugate eigenvalues) help in the understanding
of the behavior of solutions.
Laboratory 12: Additional Numerical Techniques and Stability
(3.6, 3.7 and 5.3 of the Nagle/Sa/Snider text)
In this laboratory the notion of order of a numerical method is introduced and illustrated with
numerical techniques somewhat more sophisticated than Eulers method, such as the Taylor method
of order 2 and the Runge-Kutta of order 4. Students are shown how to apply these methods to
scalar equations as well as systems. Examples and problems used in this laboratory focus on
celestial mechanics.
Laboratory 13: Introduction to SIMULINK
This laboratory is a wide departure from the other laboratory sessions in the sense that no MAT-
LAB command is needed. Instead students are shown how to assemble a SIMULINK GUI model
associated to a given system of dierential equations and use it to simulate the solution of the
model.
Laboratory 14: Laplace transform
This session considers numerical implementations of the Laplace and inverse Laplace transforms
as well as symbolic functions used to obtain these transforms (if the MATLAB Symbolic Toolbox
is available). Applications to solving linear initial value problems are included. One goal of this
lab is to make students aware of the diculty in evaluating the transform nume2ically.
38 MATLAB sessions: Laboratory 1
Laboratory 1
First-Order Dierential Equations
Graphical Analysis Using Direction Fields
(1.3 in the Nagle/Sa/Snider text)
In this laboratory session we look at scalar rst-order dierential equations from a graphical viewpoint
and make use of direction elds. Our goal is to learn how to
1. create a function for plotting the direction eld of a given ODE.
2. interpret the direction eld to obtain pertinent information about solutions to the ODE.
Direction elds
A direction eld for a scalar rst-order dierential equation is a two-dimensional t-y plot of arrows (or
line segments). If the tail of an arrow is at a point (t, y) the slope of the arrow is given by f(t, y) so that
the arrow is tangent to the solution curve passing through the point (t, y). The direction eld provides
a simple way to visualize solutions without actually solving the ODE.
Consider the ODE
dy
dt
= y
= 1 siny. (L1.1)
We use the script page 20 to create a function le dirfield.m. The inputs of the function dirfield
are the right-hand side of the ODE and the window size for the plot (in t and y directions):
dirfield.m
function dirfield(f,window,type)
% plots the direction field for the scalar ODE y=f(t,y)
% in domain specified by window using a 21x21 grid of arrows
% use: dirfield(@f,[tmin,tmax,ymin,ymax],type)
% with type = arrow or line
t = linspace(window(1),window(2),21);
y = linspace(window(3),window(4),21);
[T,Y] = meshgrid(t,y);
% evaluate slope and normalize
S = feval(f,T,Y);
N = sqrt(1+S.^2);
dT = 1./N; dY = S./N;
switch type
case arrow; quiver(T,Y,dT,dY);
case line; quiver(T,Y,dT,dY,.);
otherwise; disp(type not implemented);
end
axis tight; grid on;
Check the axis options using help axis. A driver le then calls the dirfield function:
Lab1a.m
function Lab1a
% driver for dirfield.m
window = [-10,10,-10,10];
dirfield(@f,window,arrow);
MATLAB sessions: Laboratory 1 39
title(Direction field of y=1-sin y); % note the use of
%------------------------------------------------------------
function dydt = f(t,y)
% defines right-hand side of ODE
dydt = 1-sin(y);
It is important here that f be dened in Lab1a.m so as to accept matrix arguments. Make sure both
les dirfield.m and Lab1a.m are saved in the current directory.
Try help dirfield and help Lab1a. What does MATLAB return? Type Lab1a in the Command
Window to get Fig. L1a.
10 8 6 4 2 0 2 4 6 8 10
10
8
6
4
2
0
2
4
6
8
10
Direction field of y=1sin y
Figure L1a: Direction eld of y
= 1 siny
1. Answer the following questions regarding what you see in Fig L1a.
(a) If a solution has initial value y(0) = 4 what will be its behavior as t gets larger? as t gets
smaller? Between what values will the solution y(t) remain for all values of t?
(b) What do you notice about the direction of the arrows? Can you expect this simply from
considering the ODE (L1.1)? Explain.
(c) If a solution has initial value y(0) = 4 2, what would the general shape of the solution be
compared to the case y(0) = 4? How can you justify this using the ODE?
(d) What are equilibrium (constant) solutions?
40 MATLAB sessions: Laboratory 1
(e) Use the GUI deld6.m to check the shape of the direction eld shown in Fig. L1a and draw
some of the solutions (by clicking within the direction eld window obtained) to conrm your
observations. Fig. L1b shows what you should obtain.
Figure L1b: Direction eld of y
= sint.
(b) y
= siny.
(c) y
= sint siny.
Additional Problems
4. For each of the following ODEs plot the direction eld using the method of your choice (dirfield.m
or DFIELD6) and answer the following questions:
(a) What is the behavior of solutions as t approaches ?
(b) Do small variations in initial conditions lead to large changes in the solutions as t increases?
(c) Are solution periodic? If so, what is the period?
(d) Do solutions tend to an asymptote? If so, what is that asymptote?
i. y
= 2y +
1
t
ii. y
= sint
y
2
5. For what values of t or y is the ODE y
=
t
y
dened? Illustrate and discuss the behavior of
solutions.
6. Show that a solution y = y(t) of y
(t
0
)(t
1
t
0
) +. . .
= y
0
+hf(t
0
, y(t
0
)) +. . .
= y
0
+hf(t
0
, y
0
) +. . .
For small enough h we get an approximation y
1
for y(t
1
) by suppressing the . . ., namely
y
1
= y
0
+hf(t
0
, y
0
). (L2.1)
Note that the IVP y
(t
0
) = tan =
y
1
y
0
h
,
from which (L2.1) follows.
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
s
s
y
0
y
1
y(t
1
)
t
0
t
1
= 2y, y(0) = 3.
(a) Draw the direction eld. What is the expected behavior of the solution as t gets larger?
(b) Determine the exact solution of the IVP.
(c) Determine the Euler approximations in the interval 0 t 10 using N = 2
k
steps for
k = 2, . . . , 7. Plot curves on dierent subplots of the same gure. What do you observe for
small values of N (i.e., large h)? Explain the behavior of the approximation obtained for
large N using the direction eld and the graphical interpretation of Eulers method.
Improved Eulers Method
The improved Eulers method is most easily described by considering the expression (L2.2). Using a
trapezoidal approximation for the integral leads to
y(t
1
) y(t
0
) +
h
2
(f(t
0
, y(t
0
)) +f(t
1
, y(t
1
))) ,
i.e.,
y(t
1
) = y(t
0
) +
h
2
(f(t
0
, y(t
0
)) +f(t
1
, y(t
1
))) +. . . . (L2.3)
Then substitute y(t
0
) = y
0
and dene y
1
y(t
1
) by removing the . . . in (L2.3):
y
1
= y
0
+
h
2
(f(t
0
, y
0
) +f(t
1
, y
1
)) . (L2.4)
In other words y
1
is obtained from y
0
by using an average of f values, i.e., a slope average. The equation
(L2.4) denes the trapezoidal method. Unfortunately, this formula denes y
1
only implicitly, i.e., y
1
appears on both sides of the equality so that an equation must be solved to obtain y
1
. To avoid this
problem, and since we already have made an approximation to get (L2.4), we replace y
1
on the right-
hand side by the approximation one would obtain by simply applying Eulers method from (t
0
, y
0
). The
resulting quantity
y
1
= y
0
+
h
2
_
f(t
0
, y
0
) +f(t
1
, y
0
+hf(t
0
, y
0
)
. .
Euler y
1
from (L2.1)
)
_
(L2.5)
with t
1
= t
0
+ h is the improved Euler approximation. This approximation can be thought of as a
correction to the Euler approximation. The iteration (L2.4) is then repeated to obtain y
2
y(t
2
), . . .,
i.e.,
y
n+1
= y
n
+
h
2
_
f(t
n
, y
n
) +f(t
n
+h, y
n
+hf(t
n
, y
n
))
_
t
n+1
= t
n
+h
Minor modications are made to the function euler.m to implement the improved Euler method.
MATLAB sessions: Laboratory 2 47
impeuler.m
function [tout,yout] = euler(f,tspan,y0,N)
% solves the IVP y=f(t,y), y(tspan(1))=y0 up to t=tspan(2)
% using improved Eulers method with N time steps
% use: impeuler(@f,[tmin,tmax],y0,N)
h = (tspan(2)-tspan(1))/N;
t = tspan(1); tout = t;
y = y0(:); yout = y.;
for n=1:N
f1 = feval(f,t,y);
f2 = feval(f,t+h,y+h*f1);
y = y+h*(f1+f2)/2; t = t+h;
yout = [yout; y.]; tout = [tout; t];
end
The use of the function is similar to the use of euler.m:
>> [t,y] = impeuler(f,[0,.5],3,5); % use @f if defined in separate function
>> [t,y]
ans =
0 3.0000
0.1000 3.6600
0.2000 4.4652
0.3000 5.4475
0.4000 6.6460
0.5000 8.1081
Note that the improved Euler approximation with 5 steps is already more accurate than the Euler
approximation with 50 steps! (hence the improved)
3. Consider the IVP y
= 2y, y(0) = 3.
(a) What are the improved Euler approximations using 50, 500 and 5000 steps?
(b) Compare the errors. How is the error reduction related to the ratio of numbers of steps used?
4. Consider the IVP y
= 2y 12e
2t
, y(0) = 2. How does this problem dier
from problem 2?
6. Repeat problems 2 and 4 for the IVP y
a
2
x
2
x
with y(x
0
) = 0
and a =
_
x
2
0
+Y
2
0
(hint: consider the angle and
the length of the string, see gure).
(b) Use both Eulers and improved Eulers methods with
a = 10, x
0
= 8 and N = 78 steps to obtain a numer-
ical approximation for 0.2 x 8 (i.e., h = 0.1).
(c) Compare the approximations obtained to the solu-
tion obtained using ode45.m. Compare the result
with the exact solution
y(x) = Y
0
_
a
2
x
2
+a ln
_
x
0
x
a +
a
2
x
2
a +Y
0
_
.
.......................................................
d
d
d
d
d
d
d
e
e
e
e
e
e
e
e
e
s
s
s
s
Y
0
Y
y
x x
0
i
i
i i
i i
(d) Is the trajectory independent of the velocity v? Show that x, y and t are related by
y +
_
a
2
x
2
= vt +Y
0
. (L2.6)
(e) Dierentiate (L2.6) and show that
dx =
x
a
2
x
2
a
2
vdt.
(f) Repeat part (b) using a variable h
n
=
x
n
a
2
x
2
n
a
2
vt instead, with
x
0
Y
0
a
2
vt = 0.1 (so that
h
0
= h = 0.1).
Note: euler.m and impeuler.m need to be modied since it is not a priori known how many
steps will be needed to reach x = 0.2. Use a while loop rather than a do loop.
(g) Compare the results with the ones obtained using a constant h. How many steps are needed?
Explain why h
n
< h for x x
0
and x small, but h
n
> h in some intermediate range of x
values (hard).
MATLAB sessions: Laboratory 3 49
Laboratory 3
Solution Sensitivity
(1.2 & Ch. 2 of the Nagle/Sa/Snider text)
In this session we investigate how solutions change when (small) perturbations are introduced, in par-
ticular due to numerical errors. Our objective is as follows.
1. Understand with a simple argument how small variations in initial condition can get amplied (or
reduced).
2. Identify situations where multiple solutions coexist.
First consider the IVP y
= f(t, y),
y(t
0
) = y
0
(L3.1)
at a xed time, consider y as a function of t as well as y
0
and dierentiate (L3.1) with respect to y
0
. We
obtain
y
(t) =
d
dt
y(t) =
d
dt
y(t) = (y)
(derivatives commute).
Thus y satises the linear ODE
(y)
=
f
y
(t, y(t)) y (L3.2)
(assume y(t) is known). An initial condition for y is obtained by dierentiating the IC in (L3.1):
y(t
0
) = y
0
. (L3.3)
The solution of the linear IVP (L3.2-L3.3) is given by
y(t) = y
0
exp
__
t
t
0
f
y
(s, y(s)) ds
_
. (L3.4)
The relation (L3.4) shows that a perturbation in the initial condition y
0
creates a perturbation in the
solution y(t) at a later time t > t
0
with an amplication factor exp
_
_
t
t
0
f
y
(s, y(s)) ds
_
. It encapsulates
all signicant results of interest in this laboratory session. In particular
if
f
y
> 0 perturbations are amplied (a dangerous situation),
if
f
y
< 0 perturbations are damped (a good situation),
the only way to have y(t) = 0 in regions where
_
t
t
0
f
y
(s, y(s)) ds is bounded (e.g., where
f
y
is
continuous) is to have y
0
= 0 (exp ,= 0), i.e., trajectories starting with dierent initial conditions
cannot cross,
if
_
t
t
0
f
y
(s, y(s)) ds = +for some t (in particular when
f
y
is not continuous) then innitesimally
small (0) perturbations in y
0
can create nite perturbations in y(t) (0 may be nite). This
means that two dierent trajectories starting with the same initial value are possible, i.e., the
solution may not be unique if it exists (see condition for existence and uniqueness of a solution in
the Nagle/Sa/Snider text).
Two specic situations are of interest:
MATLAB sessions: Laboratory 3 51
1. (pure integration) For ODEs of the form y
= e
t
.
The direction eld and several solution curves are shown in Fig. L3a, left. The eld direction (as
well as intensity) is the same for all points situated on the same vertical line t = cst. All solutions
are simple vertical translations of the same function.
2. (autonomous ODE) For ODEs of the form y
(y) < 0 are regions where perturbations contract. As an example consider the
ODEs y
= y (f
= y (f
= e
t
(left), y
= y (center), and y
=
t
t
2
1
y for t 0, t ,= 1.
(a) Using (L3.4) show that perturbations in the initial value contract for t < 1 and expand for
t > 1. Conrm by plotting the direction eld.
(b) Use ode45 to obtain the solutions on the interval 0 t 2 with initial condition y(0) = a
for a = 0,
1
2
, 1, 2. To do this complete and run the following m-le:
function lab3ex1
for a = [0,1/2,1/2]
[t,y] = ode45(@f,[?,?],a); % fill in time interval
plot(t,y); hold on;
52 MATLAB sessions: Laboratory 3
end
function dydt = f(t,y)
dydt = ? % fill in ODE
(c) Plot the solution curves together on the same eld. What is the maximal value of t that can
be reached? Describe the type of curves obtained.
(d) Repeat (b) with the IC y(2) = a instead but still on the interval [0, 2] (note: the step size is
negative). What is the minimal value of t that can be reached? Describe the type of curves
obtained.
2. Consider the (nonlinear) IVP
_
y
= y(1 y),
y(0) = y
0
.
(a) Draw the direction eld and solution curves corresponding to y
0
= 1, 0,
1
2
, 1, 2 using ode45.
What is the limit of y(t) as t ?
(b) Identify regions in the (t, y) plane where solutions contract and regions where solutions ex-
pand.
(c) Use euler.m to obtain an approximate solution in the case y
0
=
1
2
. Experiment with step
sizes. Is the long term approximation sensitive to the step size used?
From a numerical point of view it is important to understand not only the behavior of a particular
solution but also the behavior of nearby solutions, e.g. using the direction eld. For example the IVPs
_
y
= e
t
,
y(0) = 1
and
_
y
= y,
y(0) = 1
have a common solution y(t) = e
t
. However the two problems dier numerically.
3. Use euler.m to solve the two IVPs on the interval 0 t 2 with step size h = 0.1. Compare the
error at t = 2 obtained for both problems. Which problem is numerically better? Use also (L3.4)
to support your conclusions.
Existence and Uniqueness
An extreme case of large error amplication arises when
f
t
in (L3.4) becomes unbounded. As an example
consider a situation where a non-negative quantity y changes with respect to time at a rate equal to
twice the square root of its current value, i.e.,
dy
dt
= 2
y. (L3.5)
We recall the following existence and uniqueness result:
If f(t, y) and
f
t
(t, y) are continuous everywhere within a region containing (t
0
, y
0
) then the IVP y
=
f(t, y), y(t
0
) = y
0
, has a solution valid on some (possibly small) time interval around t
0
, and this solution
is unique.
In the case (L3.5) we have f(t, y) = 2
y and
f
t
(t, y) =
1
y
. Thus (L3.5) has a unique solution
passing through y(0) = y
0
for any y
0
> 0. For y
0
= 0 however, the result does not apply and the
solution is not guaranteed to be unique or even exist. In fact one can easily verify that y(t) = 0 and
y(t) = t
2
are two distinct solutions of the ODE (L3.5) for t 0 satisfying the IC y(0) = 0, see Fig. L3b.
4. Can you nd any other solution to the IVP y
= 2
= 2
y, y(0) = > 0.
MATLAB sessions: Laboratory 3 53
0 0.25 0.5 0.75 1
0
0.25
0.5
0.75
1
Figure L3b: Direction eld of y
= 2
)
2
is a solution.
(c) Use (L3.4) to show that y(t) = y
0
_
1 +
t
_
. How does this conrm that the IVP may not
be guaranteed to have a unique solution when = 0?
(d) Use ode45 to obtain an approximate solution in the interval [0, 1] for = 0.0001. Determine
the solution starting with y(0) =
2
instead and compute the change in the solution at t = 1.
Does this conrm the result obtained in (c)? To do this you may want to use the following
script:
epsilon = 0.0001; y0 = epsilon;
[t1,y1] = ode45(f,[0,1],y0);
[t2,y2] = ode45(f,[0,1],y0/2);
deltay = y1(end)-y2(end); % change in solution at t = 1
deltayp = (y0/2)*(1+t1(end)/sqrt(y0)); % change predicted by formula
54 MATLAB sessions: Laboratory 3
Additional Problems
6. Determine whether the solution y(t) = 0 of the ODE y
=
y
1+t
has the property that if another
solution is found whose initial value at t = 0 is close to 0 then that solution is asymptotically close
to 0 for large t (hint: use the direction eld, ode45, or (L3.4))
7. Justify why an equilibrium y
e
for the autonomous ODE y
(y
e
) < 0 and
a source if f
(y
e
) > 0.
8. Consider the (autonomous) ODE y
= 2
y, y(0) = 0.
(a) What is the numerical solution obtained by applying Eulers method? Does reducing the step
size change the numerical solution? Repeat for the improved Euler method. What is the
numerical solution obtained by using ode45?
(b) The trapezoidal method introduced in laboratory 2 is dened by
y
n+1
= y
n
+
h
2
(f(t
n
, y
n
) +f(t
n+1
, y
n+1
)) (L3.6)
for n = 0, 1, . . . Show that here (L3.6) yields y
n+1
=
_
h
2
+
_
y
n
+h
y
n
_
2
(hint: substitute
f(t, y) = 2
= y
1/3
, y(0) = 0. Verify that y(t) =
2
6
9
t
3/2
is a solution for t 0. Identity
two other solutions for t 0.
56 MATLAB sessions: Laboratory 4
Laboratory 4
Picard Iteration
(Ch. 1, Project B, page 32 in the Nagle/Sa/Snider text)
In this session we look at basic numerical methods to help us understand the fundamentals of numerical
approximations. Our objective is as follows.
1. Develop a MATLAB implementation of the Picard iteration.
2. Evaluate the use of the iteration to solve IVPs and investigate advantages/drawbacks compared
to standard procedures (Euler, ode45,...)
Primary MATLAB commands used in this laboratory are ode45 and interp1.
Picard iteration
The Initial Value Problem
_
y
= f(t, y),
y(t
0
) = y
0
involves y on both sides of the ODE. If an approximation
0
of the solution y is known, then y
f(t,
0
).
Using the initial condition we get
y(t) y
0
+
_
t
t
0
f(s,
0
(s)) ds (L4.1)
(recall that y
1
(t) = y
0
+
_
t
t
0
f(s,
0
(s)) ds. (L4.2)
(L4.2) is equivalent to
_
1
= f(t,
0
),
1
(t
0
) = y
0
.
(L4.3)
The process can be repeated, dening a sequence
n
n0
of approximations to the exact solution y:
n+1
(t) = y
0
+
_
t
t
0
f(s,
n
(s)) ds, n = 0, 1, . . . (L4.4)
or, equivalently,
_
n+1
= f(t,
n
),
n+1
(t
0
) = y
0
,
n = 0, 1, . . . (L4.5)
The iteration (L4.4/L4.5) is called Picard (xed point) iteration. Whether
n
(t) y(t) as n increases
and for what range of t values depends in general on the problem (L4.1) considered (i.e., f, y
0
), and
on the choice of initial approximation
0
(t). Without additional knowledge about the solution y(t) the
initial approximation
0
(t) = y
0
for all t
is used.
It is important to note that the Picard iteration aims at obtaining an approximate solution everywhere
in the t domain simultaneously. This is in contrast to standard methods such as euler or ode45, which
determine approximations for increasing values of t starting from t
0
.
MATLAB sessions: Laboratory 4 57
One of the main applications of Picards method is in the proof of existence and uniqueness of the
solution for rst-order initial value problems, under certain conditions of f. This proof is not considered
here. Instead we illustrate how the method works on a few examples in order to gain some understanding
of the method. In some cases this method provides a valuable tool to evaluate numerical solutions that
even sophisticated numerical solvers fail to identify.
We start with a simple example: consider the IVP y
1
=
0
,
1
(0) = 1
1
(t) = 1 +
_
t
0
0
(s) ds = 1 +
_
t
0
ds = 1 +t,
2
=
1
,
2
(0) = 1
2
(t) = 1 +
_
t
0
1
(s) ds = 1 +
_
t
0
(1 +s) ds = 1 +t +
1
2
t
2
,
3
=
2
,
3
(0) = 1
3
(t) = 1 +
_
t
0
2
(s) ds = 1 +
_
t
0
(1 +s +
1
2
s
2
) ds = 1 +
1
2
t
2
+
1
6
t
3
,
4
=
3
,
4
(0) = 1
4
(t) = 1 +
_
t
0
3
(s) ds = 1 +
_
t
0
(1 +t
1
2
t
2
+
1
6
t
3
) ds = 1 +
1
2
t
2
+
1
6
t
3
+
1
24
t
4
,
. . .
The pattern to the sequence of approximations is clear. For each n 0 we obtain
n
(t) =
n
k=0
t
k
k!
k=0
t
k
k!
= e
t
(Taylor series of e
t
).
Numerical Picard Iteration
One question is: how do we obtain the approximations
n
numerically? There are two ways to answer
this question.
1. Starting from the function
0
(t) (which can be evaluated at every t) determine the integral appear-
ing in (L4.4) using the MATLAB command quadl (type help quadl at the MATLAB prompt >>
for more info, see also quad). Numerically, the integral can be evaluated only at a specic number
npts of points t
i
. The corresponding values of
n+1
(t
i
) are then obtained from (L4.4) via the
update
1
(t
i
) =
1
(t
i1
) +
_
t
i
t
i1
f(s,
0
(s)) ds, i = 1, . . . , npts, (L4.6)
with
1
(t
0
) = y
0
. In order to determine
2
quadl must be able to evaluate
1
anywhere using
interpolation based on the points (t
i
,
1
(t
i
)) obtained, via the MATLAB function interp1 (see
the help for interp1.m).
2. A more ecient way to determine
1
from
0
(and
n+1
from
n
) is to numerically solve the IVP
(L4.3). The solution is obtained at values t
j
and so must also be interpolated when evaluated at
intermediate points when (L4.5) is solved for n = 1.
The numerical Picard iteration is illustrated in Fig. 3. MATLAB implementations of both versions are
also included.
The rst version (based on quadl) requires to set the number npts of points, while the second
version (based on ode45) does not. More importantly, the rst version is less ecient, in part because
of the evaluation of (3) inside a loop (the MATLAB routine quadl cannot evaluate multiple integrals
simultaneously). It also handles exceptions (e.g. when reaching a vertical asymptote in the solution)
less gracefully than the second version.
58 MATLAB sessions: Laboratory 4
n
(t)
n+1
(t
j
)
s
s
s
s
s
s
n+1
(t)
quadl
or ode45
E
interp1
E
Figure L4a: Numerical Picard iteration: IVP solution followed by interpolation process
picard1.m (quadl version)
function [t,y] = picard1(f,t,y,N)
% Picard iteration using quadl
TOL = 1e-6; % default, reset if desired
z = y(1)*ones(size(t));
for k=2:N
z(k) = z(k-1)+quadl(@fint,t(k-1),t(k),TOL,[],f,t,y);
end
y = z;
%-------------------------------------------------------
function dydtint = fint(t,f,told,yold)
% ODE rhs interpolated at t from (told,yold)
dydtint = feval(f,t,interp1(told,yold,t,spline));
Lab4a.m (quadl version)
function Lab4a
tspan = [0,3]; yspan = [0,20]; y0 = 1; N = 10;
window = [tspan,yspan]; t = tspan;
npts = 100; % #pts for integration
t = linspace(tspan(1),tspan(2),npts);
y = feval(@init,t,y0);
plot(t,y,r,LineWidth,2);
hold on;
for n = 1:N
[t,y] = picard1(@f,t,y,npts);
plot(t,yint,r,LineWidth,2);
end
dirfield(@f,window,arrow); % direction field, see Lab1
[t,y] = ode45(@f,tspan,y0); % "exact" solution
plot(t,y,b,LineWidth,2); % plot "exact" solution
hold off
axis(window)
%---------------------------------------------------
function dydt = f(t,y) % ODE
dydt = y;
%---------------------------------------------------
function y = init(t,y0)
% initialization for Picard iteration.
y = y0*ones(size(t)); % standard. If modified, make
% sure the new function satisfies the IC
picard2.m (ode45 version)
function [t,y] = picard2(f,t,y)
% Picard iteration using ode45
options = odeset(RelTol,1e-6,AbsTol,1e-6);
[t,y] = ode45(@fint,t([1,end]),y(1),options,f,t,y);
%----------------------------------------------------
function dydtint = fint(t,y,f,told,yold)
% ODE rhs interpolated at t from (told,yold)
dydtint = feval(f,t,interp1(told,yold,t,spline));
Lab4b.m (ode45 version)
function Lab4a
tspan = [0,3]; yspan = [0,20]; y0 = 1; N = 10;
window = [tspan,yspan]; t = tspan;
teval = linspace(tspan(1),tspan(2),100);
y = feval(@init,t,y0);
plot(t,y,r,LineWidth,2);
hold on;
for n = 1:N
[t,y] = picard2(@f,t,y);
yint = interp1(t,y,teval,spline);
plot(teval,yint,r,LineWidth,2);
end
dirfield(@f,window,arrow); % direction field, see Lab1
[t,y] = ode45(@f,tspan,y0); % "exact" solution
plot(t,y,b,LineWidth,2); % plot "exact" solution
hold off
axis(window)
%---------------------------------------------------
function dydt = f(t,y) % ODE
dydt = y;
%---------------------------------------------------
function y = init(t,y0)
% initialization for Picard iteration.
y = y0*ones(size(t)); % standard. If modified, make
% sure the new function satisfies the IC
The (common) output of Lab4a.m/Lab4b.m is shown in Fig. L4b. The direction eld (see Laboratory
1) has been superposed to check the validity of the approximation.
1. Reproduce Fig. L4b using both versions of picard. Experiment with dierent initial functions
0
(t) (e.g. t, t
2
, . . .). Compare the iterations obtained with
0
(t) = 1 + t to those obtained with
0
(t) = 1.
2. Consider the IVP y
= y, y(0) = 1.
MATLAB sessions: Laboratory 4 59
0 0.5 1 1.5 2 2.5 3
0
2
4
6
8
10
12
14
16
18
20
Figure L4b: Picard iterates
1
, . . . ,
10
starting with
0
(t) = 1 for the IVP y
= y, y(0) = 1.
(a) Determine algebraically (as in page 57) the iterates
1
, . . . ,
4
, starting with
0
(t) = 1. What
is the expected limit of the sequence
n
n0
?
(b) Use the ode45 version of the MATLAB implementation of Picards iteration to obtain the
rst 10 iterates in the window 0 t 3 (use the range 0 y 1 for plotting). Explain why
the iterates alternate above/below the exact solution.
3. The problem y
= 2t y
2
, y(0) = 0, is known to have a solution for all t > 0.
(a) Determine algebraically (as in page 57) the rst two iterates
1
and
2
.
(b) Use the ode45 version of the MATLAB implementation of Picards iteration starting with
0
(t) = 1 to obtain the rst 10 iterates in the window 0 t 3 (use the range 0 y 1
for plotting) (it takes about 90 seconds on an AMD Athlon XP 1900+ Mhz, so be patient...)
Explain what happens at t 2.5.
(c) Repeat b starting with
0
(t) = t instead, and compute the rst 20 iterates. Are the iterates
the same? Use tic ... toc to time the computation of successive iterate. What do you
notice?
Additional problems
4. Generate algebraically several Picard iterates for the initial value problem y
= 2
y, y(0) = 0.
(a) Determine algebraically (as in page 57) the iterates
n
for n > 0 when starting with
0
(t) = 0.
(b) Use the ode45 version of the MATLAB implementation of Picards iteration starting with
0
(t) = t to obtain the rst 20 iterates in the window 0 t 1 (use the range 0 y 1 for
plotting).
7. Consider the IVP y
= 1 +y
2
, y(0) = 1.
(a) Determine algebraically (as in page 57) the iterates
n
for n = 1, . . . , 6 when starting with
0
(t) = 1. How many terms seem to be accurate after each iterate? How fast does the number
of terms seem to be growing?
(b) Use the ode45 version of the MATLAB implementation of Picards iteration starting with
0
(t) = 1 to obtain the rst 10 iterates in the window 0 t 1 (use the range 0 y 1 for
plotting).
(c) What can you say about the existence of a solution to this IVP? Does it exist for all t > 0?
(d) Solve the IVP analytically and conrm your answers from the above parts.
MATLAB sessions: Laboratory 5 61
Laboratory 5
Applications of First-Order Dierential Equations
(Ch. 3 of the Nagle/Sa/Snider text)
First-order dierential equations can be used to model real world phenomena that vary with respect to
time. This section looks at some examples of this modelling. Our objectives are as follows.
1. Use dierential equations in modelling changes in population by means of the exponential, logistic,
and modied logistic population models.
2. Use dierential equations in modelling various other growth and decay problems.
3. Use dierential equations to model mixing problems.
Population Growth
Exponential growth
A simple way of modelling the growth (or decline) of a population N is to assume that the rate of change
in the population at any time t is proportional to the quantity N(t) that is present (or remaining).
Formally, this rate is change is
dN
dt
= rN. (L5.1)
Separating variables and solving for N(t) with initial value N(t
0
) = N
0
yields the exponential function
N(t) = N(t
0
)e
r(tt
0
)
. The proportionality constant r is the dierence in the per capita birth and death
rates (r = b d).
If r > 0 the population is growing, if r < 0 the population is declining (what happens if r = 0?)
Slowly reproducing species such as elephants, killer whales, and certain plants have a small r while
rapidly reproducing organisms such as bacteria, lake trout, and small insects have a large r.
Logistic growth
Equation (L5.1) exhibits unbounded population growth at an exponential rate assuming unlimited re-
sources. In comparison, logistic growth limits the size of the population. Let N
max
denote the maximum
sustainable population size (also called carrying capacity) of the habitat of study. Then N
max
N is the
number of new individuals that the habitat can accept and
N
max
N
N
max
the percentage of N
max
available for
population growth. As the population approaches the carrying capacity N
max
, the percentage of N
max
available for growth is small as a result of overcrowding and more competition for limited resources.
On the other hand the percentage
N
max
N
N
max
1 for population sizes well below the carrying capacity.
Formally the logistic population growth is then modelled by the ODE
dN
dt
= rN
N
max
N
N
max
= rN
_
1
N
N
max
_
= rN cN
2
(L5.2)
with c = r/N
max
. Equation (L5.2) succinctly shows that logistic population growth is the combination
of the process of inhibited growth with the process of competition among pairs of individuals at a rate
c.
62 MATLAB sessions: Laboratory 5
Modied logistic growth
We can modify the logistic equation (L5.2) by including the possibility that when the population size is
too small, say less than N
min
, the inability to nd a suitable mate leads to the extinction of the species.
The modied logistic equation (also called Nagumo equation) is
dN
dt
= rN
_
1
N
N
max
__
N
N
min
1
_
. (L5.3)
Note that dN/dt < 0 for 0 < N < N
min
.
Eect of stocking/harvesting
We can expand upon either model by adding (to model stocking) or subtracting (to model harvesting
or hunting) an amount > 0 for each time period. For example a logistic model with harvesting reads
dN
dt
= rN
_
1
N
N
max
_
.
Problems
1. Generate the direction elds of the exponential, logistic, and modied logistic models for population
growth and record any observable dierences. Use N
max
= 20, N
min
= 10, r = 0.8. What are the
long term trends in the population in each case? Use commands like those below.
f = inline(0.8*N,t,N);
dirfield(f,[0,10,0,30],arrow)
2. Two bacteria are placed in a petri dish with unlimited resources and growth unchecked according
to exponential law. If they divide every 20 minutes, how many bacteria are present after one day?
Write an equation that models this problem and use MATLAB to nd a numerical answer.
3. Suppose that the population of a species of sh in a certain lake is growing according to a logistic
model with r = 0.3 and N
max
= 3000. Assume that initially there are 2500 shes of that species
in the lake. Determine the correct IVP for each of the scenarios below and in each case determine
from the direction eld of the dierential equation the long term behavior of the sh population.
(a) each year 150 shes are harvested from the lake.
f = inline(????,t,y); % fill in correct ODE
dirfield(f,[0,100,0,3100],arrow);
[t,N] = ode45(f,[0,100],2500);
plot(t,N);
(b) each year 25% of the shes are harvested from the lake.
(c) what is the maximum safe xed amount to harvest each year in order to assure that there
will always be some sh in the lake?
4. The population of a species of birds in a natural preserve has been recorded each year for the past
thirteen years. We wish to determine the model which represents the behavior of this population
best:
year 1 2 3 4 5 6 7 8 9 10 11 12 13
population 34 40 46 51 55 58 60 62 63 63 64 64 64
>> years = 1:13; population = [34,40,46,51,55,58,60,62,63,63,64,64,64];
>> plot(years,population,.r,MarkerSize,20)
MATLAB sessions: Laboratory 5 63
0 2 4 6 8 10 12 14
30
35
40
45
50
55
60
65
(a) Which of the three population models (exponential, logistic, modied logistic) would you use?
(b) Make a guess for the values of the parameter(s) in your model.
(c) Solve the resulting IVP using ode45 and plot the solution together on top of the given pop-
ulation point plot above. Use an IC at t = 1.
(d) If the plots do not reasonably coincide, adjust your model.
(e) At each time t
i
= 1, 2, . . . we thus have two values for the population: the data N
i
from the
above table and the value y(t
i
) computed use ode45 for a specic guess of the parameter(s).
Evaluate the quantity
13
i=1
(y
i
y(t
i
))
2
. If your result is much larger than 0.878 adjust your
parameter(s) (say to 3 decimal digits).
(f) Does it make sense to have a model giving a non-integer population size?
Other Models, Parameter Estimation
Dierential equations similar to population models can be used to model other phenomena such as
heating/cooling, spread of diseases, and mixing problems. Here are three examples.
5. Newtons law of cooling states that the rate
dT
dt
at which the temperature T of an object
changes with time is proportional to the dierence of temperature between the object and the
ambient medium. Mathematically we write
dT
dt
= k
_
T
air
T
_
.
Milk is brought out of a refrigerator compartment kept at 40 degrees into a warm room of unknown
temperature. After 4 minutes the temperature of the milk is 54 degrees and after 6 minutes the
temperature of the milk is 59 degrees.
64 MATLAB sessions: Laboratory 5
(a) What is the temperature of the room? For this you may want to use the following program:
function lab5pb5
tdata = [4;6]; Tdata = [54;59]; % data time/temperature
k = ??; Tair = ??; % fill in initial guess
param = fminsearch(@F,[k;Tair],[],tdata,Tdata); % optimal solution
k = param(1), Tair = param(2), % optimal parameter values
%---------------------------------------
function Fv = F(param,tdata,Tdata)
k = param(1); Tair = param(2); T0 = ??; % fill-in IC
[t,T] = ode45(@f,[0;tdata],T0,[],k,Tair);
Fv = norm(T(2:end)-Tdata,2)^2;
%---------------------------------------
function dTdt = f(t,T,k,Tair)
dTdt = ??; % fill-in correct ODE
(b) When will the milk be within 1 degree of room temperature? Answer graphically or use the
commands
[t,T] = ode45(@f,[0,20],40,[],k,Tair);
i = find(T>Tair-1); t(i(1))
6. Spread of Disease. Suppose that an infectious disease is spreading among a population of
N individuals. For simplicity we will assume that the incubation period is zero and that the
changes in the progress of the decease are continuous. The population is comprised of 3 types of
individuals: infected (i individuals), susceptible (s individuals), and removed (r individuals, either
immune, dead, or removed into isolation). Susceptible individuals can become infected at a rate
proportional to both susceptible and infected population sizes si (a second-order rate of change).
Infected individuals become removed at a rate proportional to the infected population size only (a
rst-order rate of change).
s
E
a
i
E
b
r
Accordingly, the following equations hold:
ds
dt
= asi,
di
dt
= asi bi,
dr
dt
= bi. (L5.4)
Note that
d
dt
(s +i +r) = 0, i.e., s +i +r = cst = N. From (L5.4) one easily obtain
di
ds
=
asi bi
asi
=
b/a
s
1, (L5.5)
giving the rate of change of infected individuals with respect to those susceptible.
(a) Solve analytically (L5.5) for i in terms of s. Use an IC i(s
0
) = i
0
.
(b) Graph the solution for particular choices of b/a, s
0
, and i
0
. Use the following commands:
f = inline(??/s-1,s,i); % choose constant b/a
i0 = ??; s0 = ??; % select IC
[s,i] = ode45(f,[i0,2],s0); % forward solution
plot(s,i); hold on;
[s,i] = ode45(f,[i0,1e-3],s0); % backward solution
plot(s,i); hold off;
What do the graphs tell us about the relationship between the population size of infected
individuals versus the population size of susceptible individuals?
MATLAB sessions: Laboratory 5 65
7. Mixing Problem (3.2). Suppose a brine solution containing 2 kg of salt per liter runs into a tank
initially lled with 500 liters of water containing 50 kg of salt. The brine runs into the tank at a
rate of 5 liters/min. The mixture, kept uniform by stirring, is owing out at a rate of 5 liters/min.
r
out
= 5 /m
c
out
= c(t)
E
r
in
= 5 /m
c
in
= 2 kg/
E
volume
V (t)
concentration
c(t)
(a) Find the concentration c(10), in kg/, of salt in the tank after 10 minutes. Hints: note that
the volume is constant; identify the rate of change
ds
dt
of the amount of salt s(t) in terms of
r
in
, r
out
, c
in
, and c(t) and express c(t) in terms of s(t) to obtain an ODE in s(t). Use the
following MATLAB commands.
ode1 = inline(??,t,s); % fill-in ODE
[t1,s1] = ode45(ode1,[0,10],s0);
concentration1 = s1(end)/500
(b) After 10 minutes a leak develops and an additional 1 /min of mixture ows out of the tank.
What will be the concentration, in kg/, of salt in the tank 20 minutes after the leak develops?
Hints: the initial amount of salt in this question is the amount after 10 minutes calculated
in (a). Moreover the volume of the tank is now decreasing. Use the following MATLAB
commands:
ode2 = inline(10-6*s/(510-t),t,s); % explain the ODE
[t2,s2] = ode45(ode1,[10,??],s1(end)); % fill-in final time
concentration2 = s2(end)/(510-??)
What happens at t = 510 min? What is the maximal amount of salt that was in the tank at
any time before? What is the corresponding time? Hint: use the find command.
(c) Assume that the tank has an horizontal cross-section A = 50 m
2
, the leak is at the bottom of
the tank, and the rate of ow due to the leak is proportional to the height of water in the tank,
with an initial rate of 1 /min. Write an IVP giving the rate of change
dV
dt
of the volume V (t)
of water in the tank in terms of r
in
, r
out
, and V (t). Repeat (b) with the corrected volume.
Do you expect a higher or lower concentration of salt in the tank 20 minutes after the leak
develops compared to the situation in (b)? Why?
(d) Plot the concentration c(t) for 0 t 510 for all scenarios.
66 MATLAB sessions: Laboratory 6
Laboratory 6
Further Applications of First-Order Dierential Equations
(Project B of Ch. 2/Ch. 3 of the Nagle/Sa/Snider text)
In this laboratory we will examine further applications of rst-order dierential equations. These sup-
plement the applications given in the previous lab. Applications included are the snowplow problem,
aircraft guidance, and uses of Newtons law of cooling in the heating and cooling of buildings.
The Snowplow Problem
(see page 84 of the Nagle/Sa/Snider text)
One morning it began to snow very hard and continued snowing steadily throughout the day. A snowplow
set out at 8:00 A.M. to clear a road. By 11:00 A.M. 2 miles had been cleared. By 1:00 P.M. an additional
mile had been cleared. At what time did it start snowing?
Let s(t) represent the height of the snow and p(t) the distance plowed (measured in miles) as functions
of time t (measured in hours). Using t = 0 for 8:00 A.M. the problem species the following:
p(0) = 0, p(2) = 2, p(4) = 3.
Moreover s(T) = 0 for some T > 0 (t = T is the time it started to snow relative to 8:00 A.M.)
t = T
9 A.M. (t = 0)
11 A.M. (t = 2)
1 P.M (t = 4)
E
p
T
s
To construct a model for this problem, we must consider the rate of snow accumulation and the rate
of the snowplow. We will assume that it is snowing at a constant rate (steadily) and also that the rate at
which the snowplow can clear the road is inversely proportional to the height of the snow being cleared.
Thus,
ds
dt
= a and
dp
dt
=
b
s
(L6.1)
where a and b are positive constants.
1. Solve (L6.1) rst for s = s(t), then for p = p(t) using appropriate initial conditions.
2. Show that T satises the nonlinear equation
ln
_
1 +
2
T
_
ln
_
1 +
4
T
_ =
2
3
.
3. Determine T by plotting an appropriate function or using the following MATLAB commands:
MATLAB sessions: Laboratory 6 67
eq = inline(??,T); % fill-in equation in the form ?? = 0
guess = ??; % fill-in initial guess for T
T = fzero(eq,guess)
At what time (in the form ?:?? A.M.) did it start to snow? What is the value of the ratio
b
a
?
More realistically the rate at which the snowplow can clear the road is inversely proportional to the
weight of the snow being cleared, i.e., to the height times the density of the snow. As the snow piles up
it becomes more compact and we assume that the density is an increasing linear function (t) = 1 +t.
4. Derive a dierential equation model similar to (L6.1) for p = p(t).
5. Solve the model and show that T satises the nonlinear equation
ln
_
1 +
2
T
_
ln(1 + 2)
ln
_
1 +
4
T
_
ln(1 + 4)
=
2
3
.
6. Plot T as a function of for 0 0.5 using the following MATLAB commands:
function lab6pb6
A = []; T = [];
guess = ??; % use result obtained from question 3.
for alpha = 0:.01:0.5;
A = [A;alpha];
guess = fzero(@eq,guess,[],alpha);
T = [T;guess];
end
plot(A,T); grid on;
%-------------------------------------
function val = eq(T,alpha)
val = ??; % fill-in equation of the form ?? = 0
The model for (t) makes sense only if T 4 hours. What is the maximal value of that can be
used? At what time (in the form ?:?? A.M.) did it start to snow if = 0.1?
7. What happens for 0.809?
Aircraft Guidance in a Crosswind
(see Project C, Ch. 3, page 146 of the Nagle/Sa/Snider text)
An aircraft ying under the guidance of a nondirectional beacon (a xed radio transmitter, abbreviated
NDB) moves so that its longitudinal axis always points toward the beacon. The pilot sets out toward
an NDB from a point at which the wind is at right angles to the initial direction of the aircraft. The
wind maintains this direction. Assume the wind speed w and the speed a of the aircraft through the air
(its airspeed) remain constant.
E
T
x
y
%
A
T
W
T
W
68 MATLAB sessions: Laboratory 6
We place the start of the ight at (2,0) and the destination at (0,0). Let
T =
_
dx
dt
dy
dt
_
, W =
_
0
w
_
, A =
_
x
y
_
denote the velocity tangent relative to the ground (tangent to the trajectory), the wind vector, and the
velocity vector relative to the air, respectively. The quantity is a proportionality factor.
8. Express in terms of a, x, and y. Hint: the magnitude of A is equal to a. Be careful at the sign
of .
9. The vectors T, W, and A are such that T = A + W. By identifying the components on both
sides of this equation, show that the trajectory y = y(x) satises the ODE
dy
dx
=
y
x
_
x
2
+y
2
x
for x > 0, where = w/a.
10. Plot solutions corresponding to = 0, .2, .5, .9, .99 using the following MATLAB commands:
function lab6pb10
gamma = ??; % select gamma
x0 = ??; y0 = ??; % fill in initial condition
xf = 1e-3;
[x,y] = ode45(@f,[x0,xf],y0,[],gamma);
plot(x,y);
axis equal; axis([0,2,0,1])
%-------------------------------------
function dydx = f(x,y,gamma)
dydx = ??; % fill in ODE
What happens as gets closer to 1? What happens (physically) when 1?
11. For small x show that the ODE becomes
dy
dx
(1 )
y
x
. Deduce that y(x) x
1
for small x.
Verify this numerically by plotting y = y(x) in log-log scale (i.e., use loglog instead of plot).
Heating and Cooling of Buildings
(see 3.3, page 101, of the Nagle/Sa/Snider text)
A model for the change in temperature in a building is given by the ODE
dT
dt
= k(T
out
T) +k
u
(T
T). (L6.2)
The constants k and k
u
are proportionality constants in Newtons law of cooling, T
out
represents the
outside temperature, and T
T
out
T
d
) +k
u
(T
T
d
) = 0 for a desired temperature T
d
, where
T
out
is the daily average outside temperature.
12. Show that (L6.2) can be written
dT
dt
= k(T
out
T
out
) + (k +k
u
)(T
d
T).
MATLAB sessions: Laboratory 6 69
Two solutions corresponding to k = 0.5 and k = 0.25 (units/hour) are shown in Fig. 3 (k
u
=
1 unit/hour, T
d
= 75 degrees, T(0) = 70 degrees). The following MATLAB commands were used:
function lab6pb12
ku = 1;
Toutave = mean(feval(@Tair,1:24)); Td = 75;
k = 0.5;
[t,T] = ode45(@f,[0,48],70,[],k,ku,Toutave,Td);
plot(t,T,b-+);
k = 0.25;
[t,T] = ode45(@f,[0,48],70,[],k,ku,Toutave,Td);
hold on; plot(t,T,r-o); hold off;
legend(k=0.5,k=0.25)
grid on; set(gca,XTick,0:6:48)
%----------------------------------------------
function dTdt = f(t,T,k,ku,Toutave,Td)
Tout = feval(@Tair,t);
dTdt = (k+ku)*(Td-T)+k*(Tout-Toutave);
%----------------------------------------------
function Tout = Tair(t)
Tout = 80-15*cos(pi*t/12);
0 6 12 18 24 30 36 42 48
70
71
72
73
74
75
76
77
78
79
80
k=0.5
k=0.25
Figure L6a: T(t) for two values of k.
13. Which value of k represents the better insulation? Why? See what happens if there is a greater
or lesser variation of outside temperature. Write your conclusions. Is this model realistic?
70 MATLAB sessions: Laboratory 6
Improved Model
A more realistic model
dT
dt
= k(T
out
T) +U (L6.3)
is obtained with constant rates U = 8 units/hour of heat if T < T
d
and U = 6 units/hour of cooling
if T > T
d
+1. In between T
d
and T
d
+1 there is no articial heating or cooling. To solve this new setup
we start with T(0) = 70 degrees and heat the building up to a small amount dT above T
d
, or cool it
down to dT below T
d
. We use k = 0.25. The following MATLAB procedure implements this scenario
together with the previous one and plots the outside temperature for comparison.
function lab6pb12a
% basic model
ku = 1;
t = 1/60:1/60:48; Tout = feval(@Tair,t);
Toutave = mean(Tout); Td = 75;
plot(t,Tout,k,LineWidth,1); hold on;
k = 0.25; T0 = 70;
[t,T] = ode45(@f,[0,48],T0,[],k,ku,Toutave,Td);
plot(t,T,r,LineWidth,1);
% improved model
options = odeset(RelTol,1e-6,AbsTol,1e-6,Events,@events);
allt = []; allT = []; t0 = 0; t = t0;
dT = 2;
while t(end)<48
if T0<Td; U = 8;
elseif T0>Td+1; U = -6;
else U = 0;
end
[t,T] = ode45(@fi,[t0,48],T0,options,k,U,Td,dT);
allt = [allt;t]; allT = [allT;T];
t0 = t(end); T0 = T(end);
end
plot(allt,allT,b,LineWidth,1); hold off;
legend(outside,first model,improved model)
grid on; set(gca,XTick,0:6:48)
%------------------------------------------------
function [v,term,dir] = events(t,T,k,U,Td,dT)
v = (T-(Td-dT))*(T-(Td+dT)); term = 1; dir = 1;
%------------------------------------------------
function dTdt = f(t,T,k,ku,Toutave,Td)
Tout = feval(@Tair,t);
dTdt = (k+ku)*(Td-T)+k*(Tout-Toutave);
%------------------------------------------------
function dTdt = fi(t,T,k,U,Td,dT)
Tout = feval(@Tair,t);
dTdt = k*(Tout-T)+U;
%------------------------------------------------
function Tout = Tair(t)
Tout = 80-15*cos(pi*t/12);
14. Which strategy is the most comfortable?
15. Explain why the oscillations in the new model are more spaced when the outside temperature is
high (daytime).
MATLAB sessions: Laboratory 6 71
0 6 12 18 24 30 36 42 48
65
70
75
80
85
90
95
outside
first model
improved model
Figure L6b: Improved vs basic temperature control (k = 0.25).
16. Reduce the size of U to see the eect. What does this mean from a practical point of view with
regards to the capabilities of the furnace or air conditioning unit?
17. Change the tolerance dT and/or the outside temperature to see to eect on the graph.
18. (hard) The energy consumed is E
1
=
_
48
0
k
u
[T
+ 2y
vs y. Describe the behavior of the solution y (in particular in the long term).
Additional Considerations
Using euler.m
The routine euler.m described page 44 can be used without modication to nd an approximate solution
for (L7.1):
function lab7ex2
t0 = 0; tf = 12; % initial and final times
y0 = -1; v0 = 0; % initial conditions
% ode45 solution
[t,Y] = ode45(@f,[t0,tf],[y0,v0]);
y = Y(:,1); v = Y(:,2);
% Euler solution
h = 0.1; N = round((tf-t0)/h);
[te,Ye] = euler(@f,[t0,tf],[y0,v0],N);
74 MATLAB sessions: Laboratory 7
ye = Ye(:,1); ve = Ye(:,2);
figure(1); plot(t,y,b+-,te,ye,ro-); % time series for y and v
legend(ode45,Euler); grid on
figure(2); plot(y,v,b+-,ye,ve,ro-); % phase plot
xlabel(y); ylabel(v=y); grid on
legend(ode45,Euler); grid on
%------------------------------------
function dYdt = f(t,Y)
y = Y(1); v = Y(2);
dYdt = [ v ; cos(t)-4*v-3*y ];
For comparison the solution y obtained with ode45 is included in the plot, see Figure L7b.
0 2 4 6 8 10 12
1
0.8
0.6
0.4
0.2
0
0.2
0.4
ode45
Euler
1 0.8 0.6 0.4 0.2 0 0.2 0.4
0.4
0.2
0
0.2
0.4
0.6
0.8
1
y
v
=
y
ode45
Euler
Figure L7b: Time series y = y(t) (left) and phase plane v = y
_
dy
dt
= v,
dv
dt
= w,
dw
dt
= sint 4y
2
w 8yv
2
3v
with
_
_
y(0) = 1,
v(0) = 0,
w(0) = 4.
(L7.6)
This problem is implemented as follows.
function lab7ex3
t0 = 0; tf = 12; % initial and final times
76 MATLAB sessions: Laboratory 7
y0 = -1; v0 = 0; w0 = 4; % initial conditions
[t,Y] = ode45(@f,[t0,tf],[y0,v0,w0]);
y = Y(:,1); v = Y(:,2); w = Y(:,3); % extract y, v, w from Y
figure(1);
plot(t,y,b+-,t,v,ro-,t,w,mx-); % time series
legend(y(t),v(t)=y(t),w(t)=y); % note the use of
grid on; ylim([-1.5,2]);
figure(2); plot3(y,v,w); % 3D phase plot
xlabel(y); ylabel(v=y); zlabel(w=y); grid on
%-------------------------------------------------------
function dYdt = f(t,Y)
y = Y(1); v = Y(2); w = Y(3);
dYdt = [ v ; w; -sin(t)-4*y^2*w-8*y*v^2-3*v ];
The output is shown in Fig. L7d. The limit is the vertical axis of the plot on the left were deliberately set
to the same ones as in Fig. L7c for comparison purposes using the MATLAB command ylim([-1.5,2]).
0 2 4 6 8 10 12
1.5
1
0.5
0
0.5
1
1.5
2
y(t)
v(t)=y(t)
w(t)=y
1
0.8
0.6
0.4
0.2
0
0.2
0.4
0.6
0.8
1.5
1
0.5
0
0.5
1
1.5
2
4
2
0
2
4
y v=y
w
=
y
vs. y vs w = y
.
9. Is there any other value of r such that the choice v =
dy
dt
ry leads to an ODE in v which is
independent of y?
78 MATLAB sessions: Laboratory 8
Laboratory 8
The Mass-Spring System
(4.1-4.3 and 4.8 of the Nagle/Sa/Snider text)
In this laboratory we will examine harmonic oscillation. We will model the motion of a mass-spring
system with dierential equations.
Our objectives are as follows:
1. Determine the eect of parameters on the solutions of dierential equations.
2. Determine the behavior of the mass-spring system from the graph of the solution.
3. Determine the eect of the parameters on the behavior of the mass-spring.
The primary MATLAB commands use are the ode45 function and the masspring.m GUI.
Mass-Spring System without Damping
The motion of a mass suspended to a vertical spring can be described as follows. When the spring is
not loaded it has length
0
(situation (a)). When a mass m is attached to its lower end it has length
(situation (b)). From the rst principle of mechanics we then obtain
mg
..
downward weight force
+ k(
0
)
. .
upward tension force
= 0. (L8.1)
The term g measures the gravitational acceleration (g 9.8m/s
2
32ft/s
2
). The quantity k is a spring
constant measuring its stiness. We now pull downwards on the mass by an amount y and let the mass
go (situation (c)). We expect the mass to oscillate around the position y = 0. The second principle of
mechanics yields
mg
..
weight
+ k( +y
0
)
. .
upward tension force
= m
d
2
( +y)
dt
2
. .
acceleration of mass
, i.e., m
d
2
y
dt
2
+ky = 0 (L8.2)
using (L8.1). This ODE is second-order.
(a) (b) (c) (d)
y
0
m
k
. Then v
= y
=
2
y = 4y. Also v(0) = y
c
The position of the mass m is (x, y) = ( sin, cos ). The rst
principle of mechanics states that the acceleration vector A is
the sum of all forces applied to the mass, namely the weight
W, the tension in the rod T, and the friction force F opposite
to the movement and proportional to the velocity of the mass.
Thus
A = W+F +T (L9.1)
with
A = m
d
2
dt
2
_
x
y
_
= m
d
2
dt
2
_
cos
sin
_
m
_
d
dt
_
2
_
sin
cos
_
,
W =
_
0
mg
_
, F =
d
dt
_
x
y
_
=
d
dt
_
cos
sin
_
,
(g 9.8 m/s
2
32 ft/s
2
) and
T
_
x
y
_
_
sin
cos
_
(only the direction of T is known, not the magnitude).
When taking the dot product of (L9.1) with
_
cos
sin
_
the contribution of T disappears (this amounts
to projecting (L9.1) onto a direction perpendicular to the direction of the rod, i.e., in the direction of A
or F). This yields
m
d
2
dt
2
= mg sin
d
dt
, or
d
2
dt
2
+c
d
dt
+
2
sin = 0 (L9.2)
with c = /m and
2
= g/. Clearly, equation (L9.2) is nonlinear, which makes it interesting to study
since no analytical solution is available.
Our objectives are as follows.
1. Determine the eect of variations in the parameters in the solution.
2. Determine the eect of linearization of the dierential equation.
The Undamped Case
Lets rst assume that c = 0 (i.e., = 0). We solve the ODE (L9.2) subject to initial conditions
(0) = 45 degrees and
(0) = 1 rad/s, assuming = 0.5 m. The ODE is rst reduced to a set of two
rst-order ODEs
d
dt
= v,
dv
dt
=
2
sin (L9.3)
with v(0) =
(0) = 0 rad/s.
(b) (0) =
22
7
rad,
(0) = 0 rad/s.
(c) (0) = rad,
(0) = 30 rad/s.
(d) (0) = 2 rad,
(0) = 1 rad/s.
(e) (0) = 10 rad,
(0) = 0 rad/s.
(f) (0) =
220
7
rad,
(0) = 0 rad/s.
(g) (0) = 7 rad,
dt
2
+
2
= 0. (L9.4)
6. Modify the function implementing the ODE accordingly and plot both linearized and original
solutions together. Experiment with the following initial conditions and summarize what happens.
(a) (0) = 0 degree,
(0) = 2 rad/s.
(b) (0) = 0 degree,
(0) = 50 rad/s.
(c) (0) = 10 degrees,
(0) = 8 rad/s.
(d) (0) = 45 degrees,
(0) = 30 rad/s.
(g) (0) = 360 degrees,
(0) = 0 rad/s.
For each case make a judgment whether the graph accurately describes the movement of the
pendulum. Which of the graphs exhibit signicant discrepancies between original and linearized
cases? Can you explain why?
With Damping Present
Now consider a small damping coecient c in the original non-linearized equation (L9.2) and observe
the eect.
7. First reduce the ODE (L9.2) to a system of two rst-order ODEs similar to (L9.3). Modify the
example lab9ex1 accordingly.
function lab9ex2
g = ??; l = ??; m = ??; gamma = ??;
omega = ??; c = ??;
theta0 = ??; v0 = ??; % pay attention to degrees vs radians
options = odeset(Reltol,??,AbsTol,??);
[t,Y] = ode45(@f,[0,20],[theta0,v0],options,omega,c);
theta = Y(:,1);
figure(1); plot(t,??,b-); % theta in degrees
grid on
%---------------------------------------------
function dYdt = f(t,Y,omega,c)
theta = Y(1); v = Y(2);
dYdt = [ ?? ; ?? ]; % fill-in ODE
Experiment with the following cases below, using m = 1, = 1, = 0.5, and g = 9.81. In each
case comment on the behavior of the pendulum and on the accuracy of the numerical simulation
(the gures show the angle in degrees as functions of time with tolerances set to 10
12
in odeset;
you may want to increase the accuracy to check whether the numerical solution obtained remains
the same).
MATLAB sessions: Laboratory 9 87
(a) (0) = 45 degrees,
(0) = 1 rad/s.
0 2 4 6 8 10 12 14 16 18 20
40
30
20
10
0
10
20
30
40
50
(b) (0) = 180 degrees,
(0) = 0 rad/s.
0 2 4 6 8 10 12 14 16 18 20
100
50
0
50
100
150
200
(c) (0) = 180 degrees,
(0) = 10 rad/s.
0 2 4 6 8 10 12 14 16 18 20
150
200
250
300
350
400
450
500
550
88 MATLAB sessions: Laboratory 9
8. The Poe pendulum
(Poes Pendulum by Borelli, Coleman & Hobson, Mathematics Magazine, 58(2) (1985) 78-83)
Do problem 7 rst. Assume that we have now a pendulum with a length increasing over time in
the form
= (t) =
0
(1 +t)
where is a positive constant. The ODE modelling the rate of change of now becomes
d
2
dt
2
+c
d
dt
+
2
1 +t
sin = 0 (L9.5)
Compare the behavior of the Poe pendulum when = 1 and for the values from problem 7. For
each of the 3 cases of initial values, plot the solution for the Poe pendulum compared to the solution
from problem 6. What is the general change in the frequency of oscillations? What happens if the
friction term c vanishes for the initial conditions (0) = 45 degrees,
1
2
ct
sin
_
t
_
c
2
4
+
_
+Asin(t +) (L10.2)
with
A =
1
_
(
2
2
)
2
+c
2
2
, (L10.3)
sin = cA, cos =
_
2
_
A, (L10.4)
and a and are determined from the initial conditions (see 4.9 of the Nagle/Sa/Snider text). The
rst term in (L10.2) represents the general solution to the homogeneous equation (independent of )
while the second one represent a particular solution of the full ODE.
Note that when c > 0 the rst term vanishes for large t due to the decreasing exponential factor.
The solution then settles into a (forced) oscillation with amplitude A given by (L10.3). The objectives
of this laboratory are then to understand
1. the eect of the forcing term on the behavior of the solution for dierent values of , in particular
on the amplitude of the solution.
2. the phenomena of resonance and beats in the absence of friction.
The Amplitude of Forced Oscillations
We assume here that = 2 and c = 1 are xed. Initial conditions are set to 0. For each value of , the
amplitude A can be obtained numerically by taking half the dierence between the highs and the lows
of the solution computed with a MATLAB ODE solver after a suciently large time, as follows:
1 function lab10ex1
2 omega = 2; c = 1; Omega = 1.8;
3 param = [omega,c,Omega];
4 t0 = 0; y0 = 0; v0 = 0; Y0 = [y0;v0]; tf = 50;
5 [t,Y] = ode45(@f,[t0,tf],Y0,[],param);
6 y = Y(:,1); v = Y(:,2);
7 figure(1)
8 plot(t,y,b-); ylabel(y); grid on;
90 MATLAB sessions: Laboratory 10
9 t1 = 25; i = find(t>t1);
10 A = (max(Y(i,1))-min(Y(i,1)))/2;
11 disp([computed amplitude of forced oscillation = num2str(A)]);
12 Atheory = 1/sqrt((omega^2-Omega^2)^2+(c*Omega)^2);
13 disp([theoretical amplitude = num2str(Atheory)]);
14 %----------------------------------------------------------------
15 function dYdt = f(t,Y,param)
16 y = Y(1); v = Y(2);
17 omega = param(1); c = param(2); Omega = param(3);
18 dYdt = [ v ; sin(Omega*t)-omega^2*y-c*v ];
When executing this program we get
>> lab10ex1
computed amplitude of forced oscillation = 0.51163
theoretical amplitude = 0.51181
Lines 9-13 deserve some explanation. Line 9 denes a time t1 after which we think the contribution of
the rst term in (L10.2) has become negligible compared to the second term. This depends of course
on the parameter values, in particular c. With c = 1 we obtain e
1
2
ct
3.7 10
6
for t = 25, so this
is certainly small enough compared to the amplitude seen on Figure L10a. The index i of time values
larger than t1 is then determined. The quantity Y(i,1) refers to the values of y associated to times
larger than t1 only. The computed amplitude is simply half the dierence between the max and the min
values. This value is compared to the theoretical value (L10.3).
0 5 10 15 20 25 30 35 40 45 50
0.8
0.6
0.4
0.2
0
0.2
0.4
0.6
y
Figure L10a: Forced oscillation.
1. (a) What is the frequency (in radians per second) of the forced oscillation? What is the numerical
value (modulo 2) of the angle dened by (L10.4)?
MATLAB sessions: Laboratory 10 91
(b) Subtract the quantity Asin(t +) from the numerical solution, using the theoretical ex-
pressions (L10.3) and (L10.4) for A and . Plot the resulting quantity. Does it look like an
exponentially decreasing oscillation?
(c) Divide the resulting function obtained in (b) by e
1
2
ct
. Plot the function obtained, setting
the axis limits to [1, 1] in the vertical direction (using ylim). Comment on what you get.
For t 15 what is the approximate frequency of oscillations (in rad/s)? Is this in line with
the expression (L10.2)?
2. We now consider A as a function of . We use again = 2, c = 1 and y(0) = y
(0) = 0. The
previous problem determined A for a specic value of . Here we consider a range of values for
and determine numerically the corresponding amplitude A. Plot the result as a function. You
may need the following MATLAB program.
function lab10ex2
omega = 2; c = 1;
OMEGA = ??; A = zeros(size(OMEGA)); % fill-in
t0 = 0; y0 = 0; v0 = 0; Y0 = [y0;v0]; tf = 50; t1 = 25;
for k = 1:length(OMEGA)
Omega = ??; % fill-in
param = [omega,c,Omega];
[t,Y] = ode45(@f,[t0,tf],Y0,[],param);
i = find(t>t1);
A(k) = (max(Y(i,1))-min(Y(i,1)))/2;
end
Atheory = ??; % fill-in
figure(1)
plot(??); grid on; % fill-in
xlabel(\Omega); ylabel(A);
%----------------------------------------------------------------
function dYdt = f(t,Y,param)
y = Y(1); v = Y(2);
omega = param(1); c = param(2); Omega = param(3);
dYdt = [ v ; sin(Omega*t)-omega^2*y-c*v ];
1 1.2 1.4 1.6 1.8 2 2.2 2.4 2.6 2.8 3
0.15
0.2
0.25
0.3
0.35
0.4
0.45
0.5
0.55
A
Plot also the theoretical amplitude A from (L10.3) as a function of . For what approximate value
of is the amplitude of the forced oscillation maximal? Is this value comparable to the value
92 MATLAB sessions: Laboratory 10
obtained from (L10.3)? (Hint: dierentiate...) Are the results aected by changes in the initial
conditions?
Resonance
We now investigate what happens to the solution (L10.2), and more specically to the maximal amplitude
A of the forced oscillation, when we let c 0. The value of corresponding to this maximal amplitude
is called resonant frequency. When a mechanical system is stimulated by an external force operating at
this frequency the system is said to be resonant.
4. Repeat problem 2 with c = 0.
1 1.2 1.4 1.6 1.8 2 2.2 2.4 2.6 2.8 3
0
5
10
15
20
25
30
A
computed numerically
theoretical
Explain what happens. What is the maximal amplitude? What is the frequency yielding the
maximal amplitude in the forced solution? How does this frequency compare to ?
Beats
When c = 0 and is dierent from the resonant frequency the solution (L10.2) to (L10.1) is a sum of
two sine functions. When is close to the resonant frequency some interesting phenomenon, known as
beats, occurs. To see this phenomenon, set c = 0 in lab10ex1.
5. Repeat problem 1 with c = 0 (you may need to extend the time interval of simulation).
MATLAB sessions: Laboratory 10 93
0 10 20 30 40 50 60 70 80 90 100
2.5
2
1.5
1
0.5
0
0.5
1
1.5
2
2.5
y
Explain what happens. What is the period of the fast oscillation? What is the period of the slow
oscillation? How do these values vary as moves closer to the resonant frequency? moves away
from the resonant frequency?
Additional Problem
5. Experiment with the GUI masspring.m mentioned in Laboratory 8 page 81. In particular set
the parameter button ) to frequency and move the slider ) to visualize the
change in the solution when other parameters are set to values from the above examples.
.
94 MATLAB sessions: Laboratory 11
Laboratory 11
Analytical and Graphical Analysis of Systems
(5.1, 5.2, 5.4 and 9.1-9.6 of the Nagle/Sa/Snider text)
In this laboratory we consider two-dimensional linear systems of the form
_
_
dx
dt
= ax +by,
dy
dt
= cx +dy
(L11.1)
where a, b, c, and d are real constants. The system (L11.1) is written in matrix form
dx
dt
= Ax with x =
_
x
y
_
and A =
_
a b
c d
_
. (L11.2)
The objectives of this laboratory are as follows.
1. Learn how to use MATLAB to nd eigenvalues and corresponding eigenvectors to build the solution
of the ODE system (L11.1).
2. Learn how to use MATLAB to graph and interpret the phase plane for the system (L11.1).
3. Compare the system (L11.1) to equivalent systems.
Primary MATLAB commands used in this laboratory are eig, null, dirfield.
An Example
(9.5 of the Nagle/Sa/Snider text)
Consider the matrix A =
_
1 4
2 1
_
. The eigenvalues are the roots of the characteristic equation p() =
det(A I) = 0. The characteristic polynomial of A can be obtained in MATLAB with the command
poly. The eigenvalues are then computed by computing the roots of this polynomial:
>> A = [1,4;2,-1]
A =
1 4
2 -1
>> p = poly(A)
p =
1 0 -9
>> evalues = roots(p)
evalues =
3
-3
MATLAB stores polynomials by recording its coecients. The polynomial p obtained above is
p() = 1
2
+ 0 9 =
2
9.
Its roots are 3. To obtain the corresponding eigenvectors one solves the system Ax = x for each
eigenvalue , or, equivalently, nd the set of vectors x satisfying (A I)x = 0 (I is the 2 2 identity
matrix I =
_
1 0
0 1
_
). This set is called the nullspace of the matrix A I. This can be done via
MATLABs null command:
MATLAB sessions: Laboratory 11 95
>> I = eye(2,2) % define 2x2 identity matrix
I =
1 0
0 1
>> lambda1 = evalues(1) % first eigenvalue
lambda1 =
3
>> x1 = null(A-lambda1*I)
x1 =
0.8944
0.4472
Thus x =
_
0.8944
0.4472
_
is an eigenvector of A associated to eigenvalue = 3 (in fact any nonzero multiple of
this vector is also an eigenvector associated to eigenvalue 3). A quick numerical verication shows that
Ax and x match to machine accuracy.
>> A*x1-lambda1*x1
ans =
1.0e-015 *
0
-0.4441
1. Determine the eigenvector of A associated to the second eigenvalue of A.
In practice eigenvalues and eigenvectors of A are computed using a safer and more ecient procedure
implemented in the MATLAB eig command:
>> A = [1,4;2,-1]
A =
1 4
2 -1
>> evalues = eig(A)
evalues =
3
-3
>> [S,Lambda] = eig(A)
S =
0.8944 -0.7071
0.4472 0.7071
Lambda =
3 0
0 -3
When specifying a single output eig returns all eigenvalues in a vector with as many entries as the
dimension of A. To get the corresponding eigenvectors one simply use two output arguments: the
rst one is a matrix S whose columns are the eigenvectors x
1
and x
2
of A, i.e., S =
_
x
1
[x
2
. The
second matrix is a diagonal matrix (read lambda) whose diagonal coecients are the corresponding
eigenvalues, i.e., =
_
1
0
0
2
_
. In this case the eigenvalues are referenced in MATLAB as Lambda(1,1)
and Lambda(2,2).
2. The MATLAB command inv(S) determines the matrix inverse S
1
of S. Compute the matrix
product S
1
S. Do you recognize the resulting matrix? Can you explain algebraically why this
result can be expected?
3. In this problem it is possible to nd eigenvectors with integer entries. Do it. Now S is a matrix
with integer entries. What is S
1
S?
96 MATLAB sessions: Laboratory 11
We now turn to the solution of the dierential system (L11.2) (i.e., (L11.1)). From the theory we know
that the solution is
x(t) = C
1
e
1
t
x
1
+C
2
e
2
t
x
2
(L11.3)
where C
1
and C
2
are constants dened from the initial conditions. At t = 0 we obtain
x(0) = C
1
x
1
+C
2
x
2
=
_
x
1
[x
2
_
C
1
C
2
_
= S
_
C
1
C
2
_
. (L11.4)
Given the initial vector x(0), the constants C
1
and C
2
can be obtained by solving the system (L11.4).
If x(0) = 1 and y(0) = 0 then x(0) =
_
1
0
_
.
>> x0 = [1;0]; C = inv(S)*x0
C =
0.7454
-0.4714
or, better, as
>> x0 = [1;0]; C = S\x0
C =
0.7454
-0.4714
4. Write a MATLAB program to evaluate the expression (L11.3). Plot x and y as functions of t and
y vs x in the interval 0 t 2. Compare with the direct solution of (L11.1) using ode45.
Phase Plot
A phase plot is a direction eld of the ODE
dy
dx
= . . .. From (L11.1) we obtain
dy
dx
=
dy/dt
dx/dt
=
cx +dy
ax +by
.
The following MATLAB commands show how to obtain the phase plot.
>> f=inline((2*x-y)./(x+4*y),x,y)
f =
Inline function:
f(x,y) = (2*x-y)./(x+4*y)
>> dirfield(f,[-2,2,-2,2],line)
Warning: Divide by zero.
> In C:\matlabR12\toolbox\matlab\funfun\inlineeval.m at line 13
In C:\matlabR12\toolbox\matlab\funfun\@inline\feval.m at line 34
In C:\Documents and Settings\...\BDW\2003\BOOK\dirfield.m at line 9
>> axis equal tight
>> hold on
>> plot([S(1,1),-S(1,1)],[S(2,1),-S(2,1)],r,LineWidth,2)
>> plot([S(1,2),-S(1,2)],[S(2,2),-S(2,2)],r,LineWidth,2)
>> hold off
The result is shown in Figure L11a. Eigenvector directions (lines between the tips of x
1
and x
2
) have
also been plotted.
NOTE: if dirfield is used with the option arrow rather than line the direction of the arrows
may be incorrect. Why? Refer to the le dirfield.m page 38.
5. Complete the direction of the ow in Figure L11a (i.e., give an orientation to the line segments).
Justify your choice. You may want to superpose the solution of (L11.2) obtained for dierent initial
conditions to conrm your choice.
MATLAB sessions: Laboratory 11 97
2 1.5 1 0.5 0 0.5 1 1.5 2
2
1.5
1
0.5
0
0.5
1
1.5
2
Figure L11a: Phase plot with eigenvector directions for the matrix A=[1,4;2,-1].
6. Choose a smaller or larger window for plotting the phase plot. Does the resulting graph change?
Can you give a reason why?
7. Can you explain why MATLAB complains when using dirfield with the specied window? Can
you select a window so that these remarks disappear. You may need to refer to the le dirfield.m
page 38.
Multiple Eigenvalue
In some cases the 2 2 matrix A in (L11.2) has a double eigenvalue
1
=
2
but only one eigenvector
x
1
, so that a matrix S cannot be constructed as above. Instead we nd a vector y satisfying
(A
1
I)y = x
1
. (L11.5)
The vector y is called a generalized eigenvector. It can be shown that (L11.5) always has innitely many
solutions, dened up to a multiple of the eigenvector x
1
. The general solution of (L11.2) is then formed
as the combination
x(t) = C
1
e
1
t
x
1
+C
2
e
1
t
(tx
1
+y) , (L11.6)
where C
1
and C
2
are constants dened from the initial conditions.
For example consider the matrix A =
_
1 1
0 1
_
. The eigenvalues/eigenvector of A are obtained
with the MATLAB eig function:
98 MATLAB sessions: Laboratory 11
>> A = [-1,1;0,-1]
A =
-1 1
0 -1
>> [S,Lambda] = eig(A)
S =
1.0000 -1.0000
0 0.0000
Lambda =
-1 0
0 -1
The columns of the array S are, to the accuracy of the calculation, collinear. As a result S is singular
and does not have an inverse:
>> inv(S)
Warning: Matrix is close to singular or badly scaled.
Results may be inaccurate. RCOND = 1.110223e-016.
ans =
1.0e+015 *
0.0000 4.5036
0 4.5036
The phase plot of the ODE system is shown below. Note that only the line segments line up with the
origin in only one direction.
>> f=inline(-y./(-x+y),x,y)
f =
Inline function:
f(x,y) = -y./(-x+y)
>> dirfield(f,[-2,2,-2,2],line)
Warning: Divide by zero.
> In C:\matlabR12\toolbox\matlab\funfun\inlineeval.m at line 13
In C:\matlabR12\toolbox\matlab\funfun\@inline\feval.m at line 34
In C:\Documents and Settings\...\BDW\2003\BOOK\dirfield.m at line 9
>> axis equal tight
>> hold on
>> plot([S(1,1),-S(1,1)],[S(2,1),-S(2,1)],r,LineWidth,2)
>> hold off
8. (a) Extract x
1
and
1
as the rst column of S and the rst diagonal coecient of Lambda,
respectively. Compute the vector y from (L11.5) and form the solution (L11.6), with constants
C
1
and C
2
computed from initial conditions x(0) = 1 and y(0) = 0. Compare the solution to
the direct solution obtained with ode45.
(b) The IVP solved in this case is
dx
dt
= x + y,
dy
dt
= y, with x(0) = 1 and y(0) = 0. First
solve explicitly for y = y(t) and substitute in the ODE for
dx
dt
, then solve for x = x(t). Does
the solution match the results obtained in (a)?
9. Find another matrix A with double eigenvalue
1
=
2
= 1 and a single eigenvector (direction)
x
1
. Plot the phase plot. Discuss the behavior of the solutions as time increases (Hint: discuss
according to the position of the initial condition in the phase plot).
MATLAB sessions: Laboratory 11 99
2 1.5 1 0.5 0 0.5 1 1.5 2
2
1.5
1
0.5
0
0.5
1
1.5
2
Figure L11b: Phase plot with eigenvector direction for the matrix A=[-1,1;0,-1].
Complex Eigenvalues
The characteristic polynomial of A is a quadratic polynomial with real coecients. In some cases its
roots (i.e., the eigenvalues of A) are complex (and conjugate of each other, i.e., they are positioned
in the complex plane symmetrically with respect to the real axis). In this case it can be shown that
the corresponding eigenvectors are complex and conjugate as well. If the initial conditions are real the
solution of the problem (L11.1) must be real. The question is: how can we extract the solution from the
complex eigenvector information using (L11.3)?
Let A =
_
1 6
4 6
_
. As before we rst compute the eigenvalues and eigenvectors of A:
>> A = [-1,6;-4,6]
A =
-1 6
-4 6
>> [S,Lambda] = eig(A)
S =
0.7746 0.7746
0.4518 + 0.4425i 0.4518 - 0.4425i
Lambda =
2.5000 + 3.4278i 0
0 2.5000 - 3.4278i
100 MATLAB sessions: Laboratory 11
The phase plot for this problem is drawn as before and shown in Figure L11c. Note that none of the
line segments is aligned with the origin.
>> f=inline((-4*x-6*y)./(-x+6*y),x,y)
f =
Inline function:
f(x,y) = (-4*x-6*y)./(-x+6*y)
>> dirfield(f,[-2,2,-2,2],line)
Warning: Divide by zero.
> In C:\matlabR12\toolbox\matlab\funfun\inlineeval.m at line 13
In C:\matlabR12\toolbox\matlab\funfun\@inline\feval.m at line 34
In C:\Documents and Settings\...\BDW\2003\BOOK\dirfield.m at line 9
>> axis equal tight
2 1.5 1 0.5 0 0.5 1 1.5 2
2
1.5
1
0.5
0
0.5
1
1.5
2
Figure L11c: Phase plot with eigenvector direction for the matrix A=[-1,6;-4,-6].
10. What is the direction of the ow in Figure L11c?
11. Determine the solution of the initial value problem (L11.1) with x(0) = 1 and y(0) = 1 using the
expression (L11.3). The resulting quantity is a complex vector for each value of t. Plot the real
and imaginary parts separately (on two dierent axes). What is the solution of the IVP? Does
this solution match the phase plot in Figure L11c? How does the solution compare to a direct
numerical simulation of (L11.1) using ode45?
MATLAB sessions: Laboratory 11 101
Additional Problems
12. Verify numerically Eulers formula e
it
= cos t +i sint.
13. Use MATLAB to compute the eigenvalues and corresponding eigenvectors, draw the phase plane
(2D example only) and set up the solution for the given initial conditions, for the following prob-
lems.
(a) A =
_
2 6
2 1
_
, x(0) =
_
1
0
_
.
(b) A =
_
_
2 1 0
1 0 2
1 1 0
_
_
, x(0) =
_
_
1
1
2
_
_
. (Use plot3 to plot the solution)
(c) A =
_
_
2 3 0
1 0 2
1 1 0
_
_
, x(0) =
_
_
1
1
2
_
_
. (Use plot3 to plot the solution)
14. Convert the second-order linear ODE y
+3y
(t
0
)
= y
0
+hf(t
0
, y(t
0
))
= y
0
+hf(t
0
, y
0
) y
1
.
If instead we truncate the expansion after two terms we obtain
y(t
1
) = y(t
0
+h)
y(t
0
) +hy
(t
0
) +
h
2
2
y
(t
0
)
= y
0
+hf(t
0
, y
0
) +
h
2
2
_
f
t
(t
0
, y
0
) +
f
t
(t
0
, y
0
)f(t
0
, y
0
)
_
y
1
. (L12.1)
Equation (L12.1) denes the rst step of the Taylor method of order 2.
taylor.m
function [tout,yout] = taylor(f,ft,fy,tspan,y0,N)
% solves the IVP y=f(t,y), y(tspan(1))=y0 up to t=tspan(2)
% using Taylors method of order 2 with N time steps
% use: taylor(@f,@ft,@fy,[tmin,tmax],y0,N)
h = (tspan(2)-tspan(1))/N;
t = tspan(1); tout = t;
y = y0(:); yout = y.;
for n=1:N
k = feval(f,t,y);
y = y+h*k+(h^2)/2*(feval(ft,t,y)+feval(fy,t,y)*k); t = t+h;
yout = [yout; y.]; tout = [tout; t];
end
MATLAB sessions: Laboratory 12 103
As an example consider the IVP
y
= 10(y e
t
) +e
t
, y(0) = 1
with exact solution y(t) = e
t
. We compute the numerical solution at t = 1 using various step sizes
h = 0.1, 0.01, 0.001, and 0.0001. We compare the accuracy obtained with both Eulers method and
Taylors method of order 2. The following MATLAB program is used.
function lab12ex1
t0 = 0; tf = 1; y0 = 1; yexact = exp(-1);
for h = [0.1,0.01,0.001,0.0001]
N = round((tf-t0)/h);
[t,ye] = euler(@f,[t0,tf],y0,N);
[t,yt] = taylor(@f,@ft,@fy,[t0,tf],y0,N);
disp([with h= num2str(h) ...
Euler error= num2str(yexact-ye(end)) ...
Error Taylor= num2str(yexact-yt(end))])
end
%------------------------------------------------------
function dydt = f(t,y)
dydt = -10*(y-exp(-t))-exp(-t);
%------------------------------------------------------
function dfdt = ft(t,y)
dfdt = ??; % fill in partial derivative of f w.r.t. t
%------------------------------------------------------
function dfdy = fy(t,y)
dfdy = ??; % fill in partial derivative of f w.r.t. y
to execute the program enter
>> lab12ex1
with h=0.1 Euler error=0.0019667 Error Taylor=-0.00014735
with h=0.01 Euler error=0.00020357 Error Taylor=-7.1902e-007
with h=0.001 Euler error=2.0427e-005 Error Taylor=-6.8477e-009
with h=0.0001 Euler error=2.0434e-006 Error Taylor=-6.8183e-011
1. (a) If the error obtained at t = 1 can be written in the form Ch
p
what is approximately the value
of p for Eulers method? for Taylors method? (Hint: determine how the error decreases for
a decrease in h by a factor 10). The value p is called the order of the numerical method.
(b) What error do you expect for both methods for h = 0.00001?
(c) how many steps are needed to obtain an accuracy of 2 10
9
with Eulers method? How
does this number compare with the number of steps required for Taylors method?
The Taylor method of order 2 appears superior to Eulers method. However, for problems where f(t, y)
is complicated or discontinuous, the gain in eciency may be less obvious. It is also not as trivial to use
to solve systems of ODEs.
We now consider a method described in the text as Runge-Kutta method:
rk4.m
function [tout,yout] = rk4(f,tspan,y0,N)
% solves the IVP y=f(t,y), y(tspan(1))=y0 up to t=tspan(2)
% using Runge-Kutta method with N time steps
% use: rk4(@f,[tmin,tmax],y0,N)
h = (tspan(2)-tspan(1))/N;
t = tspan(1); tout = t;
y = y0(:); yout = y.;
104 MATLAB sessions: Laboratory 12
for n=1:N
k1 = feval(f,t,y);
k2 = feval(f,t+h/2,y+h/2*k1);
k3 = feval(f,t+h/2,y+h/2*k2);
k4 = feval(f,t+h,y+h*k3);
y = y+h/6*(k1+2*k2+2*k3+k4); t = t+h;
yout = [yout; y.]; tout = [tout; t];
end
2. Use the rk4 method to obtain the error at t = 1 for the problem (L11.2). What is the order of
this method?
3. What are the advantages of rk4 compared to taylor?
Application to a System of ODEs
The movement of an aircraft ying under the guidance of a nondirectional beacon was described in
Laboratory 6, page 67. The equations dening the rate of change of the position of the aircraft are given
by
_
_
dx
dt
=
ax
_
x
2
+y
2
dy
dt
= a
_
y
_
x
2
+y
2
_
(L12.2)
We now use both euler.m and rk4.m to obtain a numerical approximation to the solution of this system
with a = 1, = 0.7 and x(0) = 2, y(0) = 0, on the interval 0 t 3.9, and compare them to the
solution obtained by ode45.m.
function lab12ex2
t0 = 0; tf = 3.9; x0 = 2; y0 = 0; Y0 = [x0;y0]; N = 1000;
[t,Y] = euler(@f,[t0,tf],Y0,N);
x = Y(:,1); y = Y(:,2); plot(x,y,r-o);
hold on
[t,Y] = rk4(@f,[t0,tf],Y0,N);
x = Y(:,1); y = Y(:,2); plot(x,y,b-x); axis equal
[t,Y] = ode45(@f,[t0,tf],Y0); size(Y)
x = Y(:,1); y = Y(:,2); plot(x,y,k-); axis equal
hold off
%-----------------------------------------------------
function dYdt = f(t,Y,param)
x = Y(1); y = Y(2); a = 1; gamma = .7;
dYdt = ??;
4. (a) Explain the program lab12ex2 in a few sentences. What happens to the ode45 solution when
the nal time is increased to 3.95. What is the reason? Do euler.m and rk4.m have this
problem?
(b) Evaluate the accuracy of the solution at time t = 2 in both x and y directions when varying
the step size.
MATLAB sessions: Laboratory 12 105
Additional Problems
12. (Keplers problem) The planar movement of a planet in the gravitational eld of the sun (or a
satellite around the earth) is described by the second-order system
_
_
d
2
x
dt
2
=
x
r
3
d
2
y
dt
2
=
y
r
3
with r =
_
x
2
+y
2
. (L12.3)
The initial conditions used for this problem are x(0) = 1, y(0) = 0, x
(0) = 0, and y
(0) = 0.8.
(a) Reduce the system of ODEs (L12.3) to a system of 4 rst-order ODEs. Specify appropriate
initial conditions.
(b) Write a le kepler.m which solves the system using euler, rk4, and ode45 and plots each
solution y vs. x (use axis equal).
(c) Plot the angular momentum M = x
dy
dt
y
dx
dt
as a function of t for all three methods. Is this
quantity constant? Should it be? What can you do to improve the accuracy of the results?
13. (Arenstorf orbit) The orbit of a satellite around two planets is dened by the set of dierential
equations
_
_
d
2
x
dt
2
= x + 2
dy
dt
(1 a)
x +a
r
3
1
a
x 1 +a
r
3
2
d
2
y
dt
2
= y 2
dx
dt
(1 a)
y
r
3
1
a
y
r
3
2
with
_
r
1
=
_
(x +a)
2
+y
2
r
2
=
_
(x 1 +a)
2
+y
2
with a = 0.012277471. The initial conditions are x(0) = 0.994, y(0) = 0, x
(0) = 0 and y
(0) =
2.00158510637908252240537862224. Plot the orbit by computing the solution using euler, rk4
and ode45 in the time interval 0 t 30. What happens to the solutions? (compare to the exact
trajectory below)
1.5 1 0.5 0 0.5 1 1.5
1.5
1
0.5
0
0.5
1
1.5
Earth
Moon
106 MATLAB sessions: Laboratory 12
14. (Lorenz system) The Lorenz equations
_
_
dx
dt
= 10(y x)
dy
dt
= 28x y xz
dz
dt
= xy
8
3
z
were originally extracted from a bigger atmospheric model to bring in evidence the chaotic nature
of the model.
(a) Simulate the system in the interval 0 t 100 using euler, rk4 and ode45. Start with the
initial conditions x(0) = 8, y(0) = 8, z(0) = 27. Plot x as a function of t. Plot y vs. x and
z vs. x.
(b) How is the time series of x modied if the initial condition is slightly changed? if the time
step/the accuracy used is changed?
MATLAB sessions: Laboratory 13 107
Laboratory 13
Introduction to SIMULINK
In this laboratory we revisit the mass-spring system from Laboratory 8 and show how to create SIMULINK
models for simulating its dynamics. SIMULINK is essentially a Graphical User Interface for MATLAB
designed to facilitate the integration of models using a block diagram system engineering approach and
click-and-drag mouse operations. Simulation results can be seen on the y. In addition, you can change
parameters and conguration and immediately see what happens.
Our objectives are as follows:
1. learn how to build simple dierential equations models without any MATLAB programming with
SIMULINK.
2. Use SIMULINK to quickly visualize the numerical solution and test the outcome of changes in
parameters.
An Example SIMULINK Model: spring1.mdl
In order to get a feeling of how a SIMULINK model operates and what it can do open the spring1.mdl
model by typing entering the MATLAB command spring1 (make sure the current directory contains
the le spring1.mdl), of clicking either on the le icon or the le name in the Current Directory pane
in the MATLAB window. A new window appears, see Figure L13a.
Figure L13a: The spring1 SIMULINK model.
108 MATLAB sessions: Laboratory 13
Figure L13b: Details of the SIMULINK spring1 model.
The spring1 model includes a source (Sine Wave ) and a sink (Scope ) for visualizing results.
Parameters dening the Sine Wave can be obtained by clicking on the Sine Wave block. The four
parameters dening the function f(t) = sin(t +) are
the amplitude A
the frequency in radians per second (not rotation per second or minute)
the phase shift in radians
a sampling time used to updated the evaluation of the Sine Wave (set to 0 for continuous)
Here A = 1, = 1, and =
2
, so that f(t) = sin
_
t +
2
_
= cos t.
The source function f(t) feeds into a summation block with 3 input ports and one output port. Note
that the other two ports have a negative sign so that the two other inputs are actually subtracted rather
than added. Lets call the input above z1, the one below z2, and the output of the block z, for now, see
Figure L13b. Thus
z = cos t z1 z2. (L13.1)
The two blocks are integration blocks. If y is the output of the second (rightmost) block then y
is
the output of the rst block and
z = y
. (L13.2)
Following now the feedback loops above and below, we encounter a Gain block of the form (here the
direction has been ipped). These blocks are simply multipliers by the indicated value. Note that the
Gain block above has input y
while the Gain block at the bottom has input y. We have thus
z1 = 4 y = 4y and z2 = 1 y
= y
. (L13.3)
Combining equations (L13.1), (L13.2), and (L13.3) we then obtain
y
= cos t 4y y
, i.e., y
+y
+ 4y = cos t. (L13.4)
Equation (L13.4) is a second-order linear dierential equation modelling the displacement of a mass
m = 1 unit attached to a spring with constant k = 4 in a viscous environment with friction coecient
= 1, with harmonic forcing term f(t) = cos t.
Values of the multiplicative factors in the Gain blocks can be changed by clicking on the respective
blocks. Appropriate initial condition for (L13.4) can also be set by clicking on each Integrator block .
In our case the initial conditions were set to
y(0) = 1 (right integrator) and y
and y.
Building a Mass-Spring SIMULINK Model
When building a model from scratch SIMULINK must be started
from the MATLAB Command Window by entering >> simulink
by clicking on the SIMULINK button on the MATLAB menu
by double clicking on the item Simulink > Library browser in the MATLAB Launch Pad win-
dow.
The Library Browser window opens, see Figure L13d. A new model can be started from the menu File
> New > Model in the Library Browser window. A new window appears. To include blocks in the new
window simply drag the block needed in the new model from the Library Browser window to the new
window. Table 3.1 lists the most common blocks used in this lab.
To avoid confusion it is best to approximately position the blocks where we think they will be in the
nal version of the model we are building. Each block should be edited to set the number of input and
output ports, as well as reasonable values for parameters or ICs. Once this is done connection are made
between the blocks by simply keeping the mouse down from one output port to the input port of another
block. Blocks with no input port are called Sources, and blocks with no output port Sinks. Comments
can be added to the model by double-clicking in the model window and entering the text (which can be
edited using the right mouse button).
110 MATLAB sessions: Laboratory 13
Figure L13d: The SIMULINK Library Browser Window: Windows (left), Unix (right)
Block Name Symbol Library
Integrator Continuous
State-Space Continuous
Fcn Functions & Tables
Gain Math
Product Math
Sum Math
Mux, Demux Signals & Systems
Scope Sinks
XY-Graph Sinks
Constant Source
Sine Wave Source
Table 3.1: Common SIMULINK library block.
MATLAB sessions: Laboratory 13 111
4. Rebuild the SIMULINK model spring1 (save it as myspring1.mdl). Compare your output in the
Scope window with Figure L13c). Adjust your model if dierent.
5. Modify your SIMULINK model to represent the ODE y
+y
+ 2y = 1 + sin t.
Alternate SIMULINK Implementations
In general there is no unique way to model a given mathematical problem with SIMULINK. For example
consider the dierential equation (L13.4). Dening
x =
_
y
y
_
we obtain
dx
dt
=
_
y
_
=
_
y
cos t 4y y
_
=
_
0 1
4 1
_ _
y
y
_
+
_
0
cos t
_
= Ax +b (L13.5)
with A =
_
0 1
4 1
_
and b =
_
0
cos t
_
. Equation (L13.5) denes a rst-order system. The initial condition
for x is
x(0) =
_
y(0)
y
(0)
_
=
_
1
0
_
.
Because (L13.5) is rst-order a SIMULINK implementation only involves a single integrator . Figure
L13e shows a possible implementation. Note the use of the Mux block, which forms the vector b from
its two (scalar) components. Also, the amplication factor in the Gain block is now the 2 2 matrix A.
Finally, the Scope window now shows both components of the input vector x, i.e., y and y
.
Figure L13e: An alternate mass-spring model.
6. Verify that the model shown in Figure L13e implements the problem (L13.5).
7. Build the SIMULINK model as shown in Figure L13e. Compare the output in the Scope window
with Figure L13c).
112 MATLAB sessions: Laboratory 13
8. Write the system (L13.5) in the form
_
dx
dt
= Ax +Bcos t
y = Cx +Dcos t
where A, B, C, and D are 2 2, 2 1, 1 2, and 1 1 constant matrices, respectively. Then use
a single State-Space block to model the same problem. Your SIMULINK model should
look like
9. Figure L13f shows a SIMULINK model.
Figure L13f: A SIMULINK model
MATLAB sessions: Laboratory 13 113
This model includes three instances of the Fcn function block .
(a) Describe what problem this model solves.
(b) Implement the model and obtain the output from both Scope and XY-graph blocks.
(c) Experiment with other functions in the function blocks .
10. Consider the model shown below.
What IVP is this model simulating? Implement it in SIMULINK and compare the output with
the one obtained by using spring1.mdl.
114 MATLAB sessions: Laboratory 14
Laboratory 14
Laplace transform
Application to the solution of linear IVPs
(7 in the Nagle/Sa/Snider text)
In this laboratory session we determine the Laplace transform and inverse Laplace transforms of functions
numerically and symbolically (using the MATLAB Symbolic Toolbox). We also show how to use several
MATLAB commands to obtain partial fraction decompositions and solutions of linear IVPs. Our goal
is to
1. learn how Laplace and inverse Laplace transforms can be implemented numerically,
2. understand the diculties associated with their evaluation,
3. apply both numerical and symbolic (if available) routines to some linear IVPs.
Primary MATLAB commands are laplace, NumLaplace, ilaplace, InvLaplace, invlap.
Laplace transform
The Laplace transform of a function f(t) is given by
Y (s) =
_
0
f(t)e
st
dt. (L14.1)
The integral in (L14.1)
1. converges at t = 0 if
[f(t)[
C
t
as t 0 (L14.2)
for some C 0 and < 1, and
2. converges at if
[f(t)[ Ce
t
as t (L14.3)
for some C 0 and real .
The integral (L14.1) then converges for any s such that '(s) > .
The Laplace transform is used to solve certain IVPs (in particular linear) essentially because it
transforms ODEs into algebraic equations, which are far easier to deal with.
The Laplace transform of a function f can be obtained using the MATLAB Symbolic Toolbox (which
is a front-end to the MAPLE kernel). The following example shows how to obtain the Laplace transform
of f(t) = sin(t):
>> syms t % defines t as a symbolic variable
>> laplace(sin(t))
ans =
1/(s^2+1)
>> pretty(ans)
1
------
2
s + 1
MATLAB sessions: Laboratory 14 115
If the Symbolic Toolbox is not available a numerical approximation of (L14.1) must be computed. This
can be done by rst transforming (L14.1) using the change of variable u = e
t
, i.e., t = lnu, so that
Y (s) =
_
1
0
f(lnu)u
s1
du. (L14.4)
The following MATLAB function evaluates the integral (L14.4) for a given value of s:
NumLaplace.m
function F = NumLaplace(f,s)
tol = 1e-6;
warning off
if ischar(f), f = inline(f); end
F = quadl(@fun,0,1,tol,[],f,s);
Fe = quadl(@fun,0,1,100*eps,[],f,s);
warning on
if abs(F-Fe)>10*tol
warning([result may be inaccurate for s= num2str(s)])
end
%----------------------------------------------------------
function fv = fun(u,f,s)
fv = feval(f,-log(u)).*u.^(s-1);
The input argument f can be a string or an inline function and s is a scalar (possibly complex) value.
The integrand is dened in the function fun. The integral is evaluated using the integration routine
quadl with target accuracy tol and is compared to a value Fe computed with a higher accuracy. If the
two results dier too much a warning message is displayed.
For the above example (f(t) = sint) we obtain
>> s = 1;
>> NumLaplace(sin(t),s)
ans =
0.5000
>> 1/(s^2+1)
ans =
0.5000
>> s = 2+i;
>> NumLaplace(sin(t),s) % i = sqrt(-1)
ans =
0.1250 - 0.1250i
>> 1/(s^2+1)
ans =
0.1250 - 0.1250i
>> s = .1+i;
>> NumLaplace(sin(t),s)
Warning: result may be inaccurate for s=0.1+1i
ans =
0.2440 - 4.8873i
>> 1/(s^2+1)
ans =
0.2494 - 4.9875i
The computed F(s) is inaccurate for values s with a small real part here. This inaccuracy can in fact be
predicted by considering the integral (L14.4): for small s the function u
s1
is large for u 0, in which
case t = lnu . Since f(t) = sint oscillates for large t we cannot expect to be able to compute the
integral accurately for small s (and more generally for s with small real part).
116 MATLAB sessions: Laboratory 14
1. Use NumLaplace to compute a numerical approximation of the Laplace transform of f(t) = sint for
s = 0.1, s = 0.1+10i, s = 10. Compare to the exact values one should get. Which approximations
are accurate?
2. For what real values s can the Laplace transform of the following functions be computed numeri-
cally? In each case compare with the value of the exact transform (using a table or the Symbolic
Toolbox function laplace function).
(a) f(t) = e
t
cos t
(b) te
t
If numerical results obtained with NumLaplace cannot be trusted for all values of s, why use it at all?
In some instances the MATLAB Symbolic Toolbox (i.e., Maple) does not manage to determine the
transform. For example consider the function f(t) =
1 e
t
t
t
. Note that f
1
t
for t 0 so that
(L14.2) holds with =
1
2
and C = 2, and (L14.3) is satised with = 0 and C = 1 (why?). Thus
(L14.1) converges for any s such that '(s) > 0:
>> syms t
>> laplace((1-exp(-t))/(t*sqrt(pi*t)))
ans =
-1/pi^(1/2)*laplace((-1+exp(-t))/t^(3/2),t,s)
>> NumLaplace((1-exp(-t))./(t.*sqrt(pi*t)),1)
ans =
0.8284
The symbolic function laplace is unable to give an explicit expression of F(s) while NumLaplace has
no diculty evaluating F(s) (for s = 1 here).
3. It turns out that an explicit form of the Laplace transform of the above function f(t) can be found
as follows. Consider the function g(t) =
1e
t
t
.
(a) Use laplace to determine the Laplace transform G(s) of g(t) (if the MATLAB Symbolic
Toolbox is not available, you can use the fact that the Laplace transform of h(t) =
1
t
is
H(s) =
1
s
, as well as the property that the Laplace transform of e
at
h(t) is H(s +a)).
(b) How is f(t) related to g(t)?
(c) How is F(s) related to G(s)? What is F(s)? (if the MATLAB Symbolic Toolbox is available,
you can use the symbolic command int if you want).
(d) Evaluate F(1) and compare with the result obtained with NumLaplace above.
Inverse Laplace transform
How do we determine a function f(t) whose Laplace transform F(s) is given? In ODE and Engineering
textbooks this is normally handled using a table of Laplace transforms that covers various types of
functions F(s) encountered in practice. Functions of the form
F(s) =
P(s)
Q(s)
e
ct
(L14.5)
where P(s) and Q(s) are both polynomials with degree(P)<degree(Q) commonly arise in applications.
The term e
ct
is indicative of a delay in the inverse transform f(t) (recall that the Laplace transform of
H(t c)f(t c) is F(s)e
ct
). The fraction
P(s)
Q(s)
can always be decomposed into partial fractions that
appear in tables.
The function InvLaplace automates the partial fraction decomposition and the inverse transform
for this class of functions F(s):
MATLAB sessions: Laboratory 14 117
InvLaplace.m
function f = InvLaplace(P,Q,c,t)
% P(s) -cs
% Inverse Laplace transform of functions of the type F(s) = ---- e
% Q(s)
% Example:
% ========
% f = InvLaplace({[2,1],[1,3]},{[5,2,3,1]},10,0:.1:50) evaluates
% the inverse Laplace transform of
% (2s+1)(1+3s)
% F(s) = ------------ exp(-10s)
% 3 2
% 5s +2s +3s+1
% at t = 0:.1:50.
% Numerator P and denominator Q must be enclosed in curly brackets {...}
% Polynomial factors in P and Q are specified by their coefficients
% in decreasing powers of s.
m = length(P); n = length(Q);
p = P{1}; q = Q{1};
for i=2:m, p = conv(p,P{i}); end
for j=2:n, q = conv(q,Q{j}); end
[a,b,r] = residue(p,q);
if isempty(r)
nb = length(b);
i = [0;find(diff(b));nb];
i = diff(i)-1; d = [];
for j=1:length(i), d = [d,0:i(j)]; end
fa = zeros(size(d));
for j=1:length(d), fa(j) = factorial(d(j)); end
d = d(:); fa = fa(:); t = t(:); i = find(t>=c); t = t(i)-c; nt = length(t);
f(i) = sum(repmat(a./fa,1,nt).*exp(b*t).*(repmat(t,nb,1).^repmat(d,1,nt)),1);
f = real(f);
else
disp(The inverse transform is not a classical function.);
disp(This case is not implemented.)
end
The function InvLaplace returns an array f containing the exact values of f at the specied points in
t. It does not return an algebraic expression for f(t). The two standard MATLAB functions conv and
residue perform the multiplication of polynomials and the partial fraction decomposition respectively.
Type help conv and help residue for more info.
An example illustrating the use of is already included in the comments: plot the inverse transform
of F(s) =
(2s+1)(s+3)
5s
3
+2s
2
+3s+1
e
10s
:
>> t = 0:.1:120;
>> P = {[2,1],[1,3]}; % a list of coefficients of factors in P
>> Q = {[5,2,3,1]}; % a list of coefficients of factors in Q
>> c = 10;
>> f = InvLaplace(P,Q,c,t);
>> plot(t,f); grid on; xlabel(t); ylabel(f(t));
The result is shown in Figure L14a.
Remark: The command
>> nice(P,Q,s)
118 MATLAB sessions: Laboratory 14
(2s+1)(s+3)
--------------
5s^3+2s^2+3s+1
writes the rational function
P(s)
Q(s)
in a nicer form to verify that P and Q have been entered correctly.
0 20 40 60 80 100 120
1.5
1
0.5
0
0.5
1
1.5
2
t
f
(
t
)
Figure L14a: Inverse Laplace transform of F(s) =
(2s+1)(s+3)
5s
3
+2s
2
+3s+1
e
10s
.
The MATLAB Symbolic Toolbox function ilaplace determines the inverse transform using symbolic
operations. For example
>> syms s
>> f = ilaplace(1/(s^2+1))
f =
sin(t)
>> ezplot(f,[0,120]) % to plot symbolic functions
For the function F(s) =
(2s+1)(s+3)
5s
3
+2s
2
+3s+1
e
10s
we obtain
>> syms s
>> ilaplace(exp(-10*s)*(2*s+1)*(s+3)/(5*s^3+2*s^2+3*s+1))
ans =
2*Heaviside(t-10)*sum((-30/671*_alpha^2+35/671*_alpha+39/671)*exp(_alpha*(t-10)
),_alpha = RootOf(5*_Z^3+2*_Z^2+3*_Z+1))+7*Heaviside(t-10)*sum((-108/671*_alpha
-195/671*_alpha^2-82/671)*exp(_alpha*(t-10)),_alpha = RootOf(5*_Z^3+2*_Z^2+3*_Z
+1))+3*Heaviside(t-10)*sum((138/671-31/671*_alpha+410/671*_alpha^2)*exp(_alpha*
(t-10)),_alpha = RootOf(5*_Z^3+2*_Z^2+3*_Z+1))
MATLAB sessions: Laboratory 14 119
Not something easy to read or directly useful! The function ilaplace cannot write the roots of Q(s) =
5s
3
+2s
2
+3s+1 symbolically and simply calls them alpha. As a result the MATLAB Symbolic Toolbox
function ezplot is unable to plot the function f(t) in this form.
For more general function F(s) than those of the form (L14.5) ilaplace may also have some problems.
Numerical approximations to the inverse transform at a given value t may be obtained from an integral
formula. This formula is generally not mentioned in textbooks because it is not trivial to apply it even
to simple Laplace transforms such as F(s) =
1
s
, let alone to more complex functions. It is sucient here
to remark that this formula requires the knowledge of F(s) for complex values s and not simply for real
values (i.e., a plot of F(s) for s real is not sucient to get an idea of f(t)!). Numerical evaluation of the
integral formula requires sophisticated techniques and is still the source of intensive research.
One MATLAB function for numerically evaluating the inverse transform of a given function F(s) is
called invlap.m and can be found at www.mathtools.net/Basic/Mathematics/MATLAB/. We use it to
obtain the inverse transform for the problem of Figure L14a:
t = .1:.1:120;
f = invlap(@F,t,0);
plot(t,f); grid on; xlabel(t); ylabel(f(t));
%------------------------------------------------------
function Fv = F(s)
Fv = exp(-10*s).*(2*s+1).*(s+3)./(5*s.^3+2*s.^2+3*s+1);
0 20 40 60 80 100 120
1.5
1
0.5
0
0.5
1
1.5
2
t
f
(
t
)
Figure L14b: Numerical inverse Laplace transform of F(s) =
(2s+1)(s+3)
5s
3
+2s
2
+3s+1
e
10s
using invlap.
The inverse transform in Figure L14b is identical to that in Figure L14a up to time t 85. For large t
(i.e., for small s) the result returned by invlap is totally inaccurate and cannot be used to determine
the long time behavior of f(t). How large can t be? This depends on the function F(s). In general
functions f(t) with many discontinuities are harder to recover than smooth ones.
4. Redraw Figure L14b (or Figure L14a) and examine the behavior of the inverse transform around
120 MATLAB sessions: Laboratory 14
t = 10. Does the function exhibit a discontinuity at t = 10? What is the size of the jump? Can
you justify this value? (Hint: lim
s
sF(s) = lim
t0
f(t) for F).
5. Determine the inverse transform of the following functions using invlap and, when possible,
InvLaplace. Comment on the results.
(a) F(s) =
1
(s + 1)(s + 2)
(b) F(s) =
1
s
2
+ 1
(c) F(s) =
e
5t
(s + 0.1)(s
2
+ 0.01)
(d) F(s) =
1
s
5
(e) F(s) =
e
s
s + 1
+
e
2s
s + 2
(f) F(s) =
1
(s + 1)(1 +e
s
)
(g) F(s) = ln
_
1 +
1
s
2
_
(h) F(s) =
1
s
2
1
s(e
s
1)
Inverse Laplace transform using SIMULINK
We introduced SIMULINK in Laboratory 13. Here we build a simple model to obtain a graph of the
inverse transform of functions F(s) of the form (L14.5) using the Transfer Function block and
the Step Function block . The example of the function F(s) =
2s
2
+5s+3
5s
3
+2s
2
+3s+1
e
10s
is shown in Figure
L14c.
Figure L14c: SIMULINK model for the Laplace transform inversion.
To understand why the transfer function appearing in the Transfer function block is
2s
3
+ 5s
2
+ 3s
5s
3
+ 2s
2
+ 3s + 1
and not
2s
2
+ 5s + 3
5s
3
+ 2s
2
+ 3s + 1
recall that the Laplace transform of the Heaviside (step) function H(t c)
is H(s) =
e
cs
s
. The model then outputs (on the Scope) the inverse transform of
2s
3
+ 5s
2
+ 3s
5s
3
+ 2s
2
+ 3s + 1
e
cs
s
=
2s
2
+ 5s + 3
5s
3
+ 2s
2
+ 3s + 1
e
10s
= F(s).
The output shown Figure L14d is obtained by double-clicking on the Scope (some of the parameters
such as the nal simulation time can be changed using the Simulation > Simulation Parameters...
menu).
MATLAB sessions: Laboratory 14 121
Figure L14d: Output for the SIMULINK model of Figure L14c.
A factor of the form
1
1e
cs
in F(s) indicates that the inverse transform f(t) is periodic with period
c. To determine the inverse transform numerically it suces to remove this factor and determine the
inverse transform of the resulting function for 0 < t c. For example consider the function
F(s) =
1
s(1 +e
s
)
=
1 e
s
s(1 +e
s
)(1 e
s
)
= G(s)
1
1 e
2s
with G(s) =
1 e
s
s
.
The function f(t) is then the 2-periodic prolongation of the function g(t) which is the inverse transform
of G(s) computed on the interval 0 < t 2. Using InvLaplace we obtain
>> t=0:.1:2;
>> f=InvLaplace({[1]},{[1,0]},0,t) ...
-InvLaplace({[1]},{[1,0]},1,t);
>> plot(t,f)
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
while using invlap yields
122 MATLAB sessions: Laboratory 14
function test
t=.1:.1:2;
f=invlap(@F,t,0);
plot(t,f)
%----------------
function Fv = F(s)
Fv = (1-exp(-s))./s;
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
0.2
0
0.2
0.4
0.6
0.8
1
1.2
6. Comment on the dierences between the output of the two graphs. What happens when using
more points in t? How can the function f(t) be plotted on the interval [0, 4]? On any interval?
7. Determine the inverse transform of the following functions
(a) F(s) =
20(1 e
s
)
s(s
2
+ 4s + 20)(1 +e
s
)
(b) F(s) =
1
s(1 +e
s
)(1 +e
2s
)
Application to the solution of initial value problems
We now apply the functions NumLaplace, InvLaplace, and invlap to the solution of linear initial value
problems of the form
c
1
y
(n)
+c
2
y
(n1)
+ +c
n
y
+c
n+1
y = f(t) with y(0) = y
0
, . . . , y
(n1)
(0) = y
(n1)
0
given. (L14.6)
The solution of the IVP (L14.6) is the sum
y(t) = y
h
(t) +y
f
(t)
of the solutions of the homogeneous problem
c
1
y
(n)
h
+c
2
y
(n1)
h
+ +c
n
y
h
+c
n+1
y
h
= 0 with y
h
(0) = y
0
, . . . , y
(n1)
h
(0) = y
(n1)
0
given, (L14.7)
and the forced problem with 0 initial conditions
c
1
y
(n)
f
+c
2
y
(n1)
f
+ +c
n
y
f
+c
n+1
y
f
= f(t) with y(0) = 0, . . . , y
(n1)
(0) = 0. (L14.8)
The Laplace transform of y is
Y (s) = Y
h
(s) +Y
f
(s) =
P(s)
Q(s)
+
F(s)
Q(s)
(L14.9)
with Q(s) = c
1
s
n
+ c
2
s
n1
+ + c
n
s + c
n+1
. The polynomial P(s) depends on the initial conditions
y
0
, . . . , y
(n1)
0
. If y
0
= . . . = y
(n1)
0
= 0 then P(s) = 0. The function F(s) represents the Laplace
transform of f(t).
We now assume that F(s) is given and of the form (L14.5). In this case both fractions in
(L14.9) are also of the form (L14.5) so that InvLaplace can be used to obtain the solution y(t) at sample
points t. The following example illustrates how the solution of the IVP y
(0) = 0, is obtained:
Lab14.m
function Lab14
% Solution of the IVP y+4y = sin(t) with y(0)=1, y(0)=0
% using Laplace transforms; assumes Laplace transform of forcing term is given
MATLAB sessions: Laboratory 14 123
c = [1,0,4]; IC = [1,0]; % ODE coefs and ICs
t = .1:.1:20;
[P,Q] = free_response(c,IC);
disp(Laplace transform of y_h =); nice(P,Q,s)
FP = {[1]}; FQ = {[1,0,1]};
disp(Laplace transform of f(t) =); nice(FP,FQ,s)
YP = FP; YQ = cellprod(FQ,Q);
disp(Laplace transform of y_f =); nice(YP,YQ,s)
y_h = InvLaplace(P,Q,0,t);
y_f = InvLaplace(YP,YQ,0,t);
y = y_h+y_f;
plot(t,y_h,k+-,t,y_f,b-,t,y,ro-,MarkerSize,5)
legend(free response (forcing = 0),response of forcing (IC = 0),total response)
The function free response determines the polynomials P and Q in Y
h
(s). The Laplace transform
of f(t) = sint is F(s) =
FP(s)
FQ(s)
where FP and FQ are given polynomials. Here FP(s) = 1 and
FQ(s) = s
2
+ 1. As a result the second fraction in (L14.9) can be written
F(s)
Q(s)
=
FP(s)
FQ(s)Q(s)
. The
function cellprod then determines the product FQ(s)Q(s) as a single polynomial in the appropriate
format suitable for use in InvLaplace.
0 2 4 6 8 10 12 14 16 18 20
1.5
1
0.5
0
0.5
1
1.5
free response (forcing = 0)
response of forcing (IC = 0)
total response
Figure L14e: Solution of the IVP y
+ 5y
+ 4y = 0 with y(0) = 1, y
(0) = 0, y
(0) = 4, y
(0) = 1.
(b) y
+ay
+ 4y =
_
sint for t <
2
1 for t 1
with y(0) = 1, y
(0) = 0.
(d) y
(0) = 0.
MATLAB sessions: Laboratory 14 125
0 2 4 6 8 10 12 14 16 18 20
1.5
1
0.5
0
0.5
1
1.5
free response (forcing = 0)
response of forcing (IC = 0)
total response
Figure L14f: Solution of the IVP y
+ 4y = sin t, y(0) = 1, y
.
At the time of this analysis, the best constants were A = 12.2 m/s and = 0.892 s.
1. What is an appropriate initial condition for this problem?
2. In your own words, explain each of the terms in the dierential equation and how the terms combine
to form a complete model. What is an interpretation of the two parameters A and ? Does the
dierential equation seem reasonable in your experience? Do you know any other situation that
could be described using this same model?
Finding and Interpreting Solutions
One reason for solving dierential equations is to derive further consequences from the solution. The
next set of questions explores the solution and its consequences.
3. Solve the IVP for v = v(t) numerically using ode45.m or euler.m.
4. Determine numerically the distance d = d(t) travelled as a function of t (use trapz.m or quadl.m,
or solve another IVP satised by d).
5. Find the acceleration a = a(t) function by dierentiating v numerically (use the diff function).
Also, write a dierential equation satised by a. What is the initial condition? Solve directly this
dierential equation numerically and compare to the result obtained from using diff.
6. Draw a graph of the distance, velocity, and acceleration over a reasonable time interval using the
1973 parameters. When does the maximum acceleration occur? How long does it take for the
acceleration to drop to 10% of its maximum value?
7. What is the runners maximum speed? How long does it take for the runner to reach 90% of this
maximum? Compare the nal speeds in a 100 meter and a 200 meter race. Explain your ndings.
8. Answer the previous two questions for general values of A and (graphically or algebraically).
Extending the Problem (Parameter Estimation)
Another aspect of dierential equations is to use the solution to estimate the parameters of the problem.
This is a form of inverse problem, a sometimes dicult problem and active research area in applied
mathematics.
Race ocials often record the split times of runners in addition to nal times. Split times are the
measure of time required to cover portions of the distance. Table 1 lists the results for the top four men
and women in the 100 meter nal at the 1993 World Track and Field Championships held in Stuttgart,
Germany.
9. Plot the data points on the same plot as the d curve obtained using the 1973 parameters. Does
the curve t the data points?
10. Determine values for the parameters A and based on the data from the Table (use the MATLAB
function fminsearch, see Lab 5 page 64)
Additional Project Descriptions 131
Name Sex Nation 30m 60m 80m 100m
Linford Christie M GRB 3.85 6.45 8.15 9.87
Andre Cason M USA 3.83 6.43 8.15 9.92
Dennis Mitchell M USA 3.82 6.46 8.22 9.99
Carl Lewis M USA 3.95 6.59 8.30 10.02
Gail Devers W USA 4.09 6.95 8.86 10.82
Merlene Ottey W GHA 4.13 6.98 8.87 10.82
Gwen Torrence W USA 4.14 7.00 8.92 10.89
Irina Privalova W RUS 4.09 7.00 8.96 10.96
Table 1: Split times (in seconds) for 100m sprint, 1993 World Track and Field Championships.
Courtesy of Shawn Price of Track and Field News
Summary and Conclusions
The theoretical analysis and the work that you have done with the data should give you a better insight
into this model. To conclude the project, lets consider a few of the following points.
11. Is it preferable to accelerate quickly at the start and then maintain the speed or to hold back
and accelerate gradually? How would the model change to allow for weakening, i.e., deceleration,
towards the end of the race?
12. Are the results produced by the model reasonable? Why does Keller suggest that this model is
valid only for races up to 300 meters? do you agree with this? What types of modications would
be needed for longer races (e.g., 1600 meters, 10 kms or marathon)?
Bibliography
[1] Alexandrov, I. and Lucht, P., Physics of Sprinting, American J. Physics 49 (1977).
[2] Dunbar, S. R., The ODE of World-Class Sprints, C-ODE-E Newsletter (Spring 1994) 7-9.
[3] Keller, J. B., A Theory of Competitive Running, Physics Today (Sept. 1973) 43.
[4] Pritchard, W. G., Mathematical Models of Running, SIAM Review 35 (Sept. 1992) 359-379.
[5] Thompson, W. J., Computing in Applied Science, Wiley (1984) 107-109.
132 Additional Project Descriptions
P3. Consecutive Reactions for Batch Reactors
Understanding the Model
Consider rst-order reactions involving three substances, A, R, and S, which are carried out isothermally
in either the gas or liquid phase in a perfectly mixed batch reactor. The reaction begins with a pure
sample of component A. The process can be schematically represented as
A
k
1
R
k
2
S
where k
1
is the reaction rate for the conversion of A into R and k
2
represents the reaction rate for the
conversion of R into S.
The primary objective is to determine the amount of each substance in the reactor as a function
of time after the reactor starts. Additional information that is desired includes the time at which the
substance R is maximum and the time at which the amount of S exceeds that of A.
Mathematical Formulation/Modelling
The concentrations of A, R, and S at any time are denoted by [A], [R], and [S], respectively. First-
order reactions means that the rate at which the component appear of disappear are proportional to
the amount present in the reactor.
1. Write a mathematical model describing the evolution of all three concentrations over time. Your
model should contain three dierential equations with appropriate initial conditions. For example
the equation describing changes in [R] reads
d[R]
dt
= k
1
[A] k
2
[R]
(in the rst reaction [A] disappears, and [R] appears, at a rate k
1
[A]).
2. Identify all mathematical information needed to answer the questions posed at the end of the
section Understanding the model.
Solution and Analysis
3. Simulate numerically the solution of your system in the cases
(a) k
1
= 1, k
2
= 3,
(b) k
1
= 3, k
2
= 1,
(c) k
1
= k
2
= 2.
4. Use the ideas from rst-order linear equations to nd analytic solutions for [A], [R], and [S]. Be
sure to nd solutions for all possible combinations of k
1
and k
2
(both positive).
Summary and Extensions
Use your ndings to provide complete answers to the questions posed at the end of the rst section for
any positive constants k
1
and k
2
. How is the model modied if one assumes that the rst reaction is
now reversible in the form A
k
1
k
3
R? What if the reaction is second-order?
Bibliography
[1] Holland, C. D. and Anthony, R. G., Fundamentals of Chemical Reaction Engineering, Prentice-Hall
(1979).
Additional Project Descriptions 133
P4. Normal T-Cells
Background
In [3] Perelson, Kerschner, and DeBoer present a model for the interaction of T-cells and HIV. In this
project we examine a preliminary model which explains the normal functioning of T-cells. The model
of T-cell formation in the presence of HIV is discussed in the project T-cells in the Presence of HIV.
The general goal of this project is to explain a biological theory. Throughout the investigation
mathematical problems are encountered, formulated, solved, and interpreted. An even more informative
view can be obtained by comparing this discussion with the original one in [3].
Basic Model
T-cells are a natural and essential component of the human immune system. The primary job of T-
cells is to attack and destroy cancerous cells, cells infected with a virus, and, in general, any cell
containing foreign antigens. Prior to examining the interaction between T-cells and HIV, it is necessary
to understand a little about how T-cells function under normal conditions.
The typical T-cell count in a healthy person is about 1000-1200 per cubic millimeter. T-cells are
created in the lymphatic tissues (including the thymus). These tissues normally produce T-cells at a
uniform (constant) rate s, but when a need is detected to combat a virus additional T-cells are created.
T-cells only live for a nite period of time.
A mathematical model for the number T of T-cells in the body as a function of time t (measured in
days) must account for the two dierent mechanisms controlling the production of T-cells and the death
of T-cells as they age. Assuming a logistic growth model for the need-based production of T-cells, and
a constant per-capita death rate , this model takes the form
dT
dt
= s +rT
_
1
T
T
max
_
T = f(T).
The parameters s, r, T
max
, and are all positive. Note that this model does not take into account the
death of T-cells due to the presence of the virus, simply the natural propensity of T-cells to respond to
the attack by the virus.
Understanding the Basic Model
1. What are the units associated with each of the parameters?
2. Explain why the conditions f(0) > 0 and f(T
max)
> 0 assure that the number of T-cells will stay
between 0 and T
max
. Under what constraints on the parameters are these conditions satised?
3. The fact that f is continuous and changes sign in the interval [0, T
max
] implies, by the Intermediate
Value Theorem, that there is some value T
?
Determine T
explicitly in terms of s, r, T
max
, and . Identify two parameters (functions of s, r,
T
max
, and ) the ratio T
/T
max
depends on.
Qualitative Analysis for a Specic Case
Realistic values of the parameters are s = 10, r = 0.03, T
max
= 1700, and = 0.02.
4. Do these values satisfy the constraints identify earlier? Numerically determine the value T
(e.g.,
obtained after t = 100 using ode45)? Is this consistent with the biological descriptions and the
analytic result?
5. Determine the behavior of solutions for initial conditions between 0 and T
max
. Do all solutions
stay in the desired interval?
134 Additional Project Descriptions
Qualitative Analysis for the General Case
We now investigate the behavior of
T
T
max
as a function of =
r
and =
s
rT
max
.
6. Select a grid of point in the (, ) domain around the point corresponding to the specic case
above. For each point in the grid numerically compute an approximation to T
r
r
r
r
r
E
R
r
L
C
Figure 1: 2-loop network
The objectives are to determine steady-state currents (as functions of the resistance r), identify the
dierent qualitative behaviors of the transient currents, and investigate the length of time required for
the currents to converge to within a given tolerance of the steady-state currents.
Mathematical Formulation/Modelling
Denote the current in the left and right loops by I
1
(t) and I
2
(t), respectively. First-order dierential
equations for these currents can be obtained by applying Kirchhos voltage law (3.5 of the Nagle, Sa
& Snider text) to each loop of the network.
1. Write Kirchhos law for each loop. Manipulate the equations until they have the form
_
dI
1
/dt
dI
2
/dt
_
= A
_
I
1
I
2
_
+b
where A is a 2 2 matrix and b a 2-dimensional vector both depending on r. What are the initial
conditions?
2. How are the equations changed if the rst loop contains also a
1
2
Farad capacitor.
Solution and Analysis
3. Determine the steady state solution as a function of the resistance r, both algebraically and nu-
merically.
4. Plot the two eigenvalues of A in the complex plane as r varies. For what values of r do solutions
oscillate?
5. Determine as a function of r the amount of time required to ensure that the current in each loop
is within 10% of the steady-state value.
6. The network is rated to support a maximum current of I
max
= 3 Amperes. What resistance r will
guarantee that the current in the network never exceeds this limit?
Additional Project Descriptions 139
Summary and Conclusion
The network considered here is not very sophisticated. While the problem would involve more variables
and the manipulations would be more dicult for more complicated networks, the same analytical and
numerical tools can be used to determine answers to the same set of questions.
140 Additional Project Descriptions
P7. The Dynamics of Love
Background
Francesco Petrarca (also known as Petrarch) was a scholar and poet in 14
th
century Italy who fell in love
with Laura, a beautiful but married lady of Avignon, France, when he was 23. Over the next 21 years
Petrarch would write a collection of 366 poems in her honor, eventually published as the Canzoniere.
These poems express a wide range of emotions, from extreme elation to deep despair. However the time
line of when these poems were written is unclear and scholars have expanded considerable eort over the
years trying to bring some temporal order into this work. In [1] S. Rinaldi developed a relatively simple
dierential equation model expressing the emotions of Petrarch and Laura, recreating a chronology for
the various poems.
In this project we focus on two aspects of this model. The rst goal is to replicate the results obtained
in [1]. The second phase explores changes in the outcome of the model when parameters are changed,
in particular regarding the existence of a steady-state.
Understanding the Model
Laura is described by a single variable L(t) representing her attitude towards Petrarch. Positive values
indicate sympathy and aection while negative values mean coldness and antagonism. Petrarch, on
the other hand, is described by two variables: his love P(t) for Laura, and his poetic inspiration I(t).
High values of P correspond to ecstatic love, while low (negative) values indicate despair. The model
developed by Rinaldi reads:
dL
dt
=
1
L +
1
_
P
_
1 P
2
_
+A
P
,
dP
dt
=
2
P +
2
_
L +
A
L
1 +Z
_
,
dI
dt
=
3
I +
3
P.
The parameters
i
and
i
, i = 1, 2, 3 are positive numbers. The quantities A
P
and A
L
describe the
physical appearance of Petrarch and Laura. Admittedly A
P
< 0 while A
L
>> 0.
1. The constants
i
are called forgetting coecients. Explain. What do you think about the
respective size of
1
and
2
?
2. Explain in plain English the contribution of the dierent terms in the equations and their eect
on the rate of change of the variables L, P, and I.
Simulation and Perturbation
Rinaldi estimated parameter values based on his own interpretation of selected poems and a calibration
with recent literary studies, and obtained the following values (with t measured in years):
1
= 3.6,
2
= 1.2,
3
= 0.12,
1
= 1.2,
2
= 6,
3
= 12, A
L
= 2, A
P
= 1.
3. What are suitable initial conditions for P(0) and L(0)? Knowing that Petrarch wrote his rst
poem about Laura years after they rst met, what is a reasonable initial condition for I(0)?
4. Simulate the IVP obtained over 21 years. Draw a plot of P and L as well as phase plots P vs L
and Z vs P. What do you observe? (is there a steady-state?)
5. What is the minimal value of
1
that yields a steady-state solution (all other parameters being
xed)? Experiment with varying other parameters to obtain a similar behavior (hint: s must be
increased, s decreased, and physical appearances A
P
and A
L
get closer to 0, i.e., neutral). What
do you think is the most sensitive parameter in the model?
Additional Project Descriptions 141
We now keep the ratio
3
/
3
and all other coecients constant at their level used above and want to
estimate the period of oscillations in T as a function of
3
.
6. Determine numerically the period of oscillations for
3
= 0.1, 0.01, and 0.001. Is the period
sensitive to the changes? Is the period increasing or decreasing? Could you predict this?
Conclusions
The model of love dynamics investigated in this project can be adapted to ones personal data. In the
case of Petrarch and Laura, it provides a fairly accurate match for data obtained independently through
literary analysis.
Bibliography
[1] S. Rinaldi, Laura and Petrarch: an intriguing case of cyclical love dynamics, SIAM Journal on
Applied Mathematics 58(4) (1998) 1205-1221.
[2] Durling, R. M. (Ed.), Petrarchs Lyric Poems, Harvard University Press, 1976.
[3] Strogatz, S. H., Love aairs and dierential equations, Math. Magazine 61 (1988) 35.
142 Additional Project Descriptions
P8. Hypergeometric Functions
The hypergeometric dierential equation is the linear second-order ODE
x(1 x)y
+ ( ( + + 1)x)y
y = 0 (1)
with parameters , , and . For ,= 0, 1, 2, . . . the method of Frobenius yields a solution to this
equation as a power series
y(x) = 1 +
x +
n=2
()
n
()
n
n!()
n
x
n
= F(, , ; x) (2)
where (a)
n
= (a +n 1) (a + 1) for n = 2, 3, . . . This function is called hypergeometric function.
The interest in such functions is that mostly any linear homogeneous second-order ordinary dieren-
tial equations can be transformed into the hypergeometric dierential equation. A number of properties
of hypergeometric functions were established in 8.8 of the Nagle/Sa/Snider text. In this project we
propose to verify numerically and, in some instances algebraically, some of these identities, as well as
evaluate the convergence of the series (2).
Basic Identities
1. What are the initial conditions satised by F(, , ; x)?
2. Prove the identity F(1, 1, 1; x) =
1
1x
. What is the radius of convergence of the series (2) in this
case?
3. Write a MATLAB function hypergeom.m which evaluates the function F at given points x
1
,. . .,x
m
by solving numerically the ODE (1) with ode45 (increase the default accuracy of the numerical
integration using odeset). Test your routine by checking the following identities
(a) F(1, 1, 1;
1
2
) = 2,
(b) F(
1
3
,
2
3
,
5
6
;
27
32
) =
8
5
,
(c) F(
1
3
,
2
3
,
5
6
;
27
32
) =
8
5
.
Hypergeometric and Elementary Functions
4. Prove or disprove, numerically and/or analytically, the following identities. Specify the domain of
validity of the identities.
(a) F(
1
2
,
1
2
,
1
2
; sin
2
x) = cos x,
(b) F(
1
2
,
1
2
,
3
2
; x
2
) =
arcsin x
x
,
(c) F(
1
2
, 1,
3
2
; x
2
) =
arctan x
x
,
(d) F(1, 1, 2; x) =
ln(1+x)
x
,
Hypergeometric Functions and Dierential Equations
5. Prove that the identity
d
dx
F(, , ; x) =
_
x
0
F(+
1, + 1, + 1; t) dt.
Additional Project Descriptions 143
6. Set = = 1 and =
1
2
. The hypergeometric function F(1, 1,
1
2
; x) then satises the ODE (1).
Show algebraically or numerically that
xF(
3
2
,
3
2
,
3
2
; x) is a linearly independent solution to (1) for
0 < x < 1.
Hypergeometric Functions and Polynomials
7. For what values of and/or is F(, , ; x) a polynomial?
8. Show the identity F(m+ 1, 1, 2; x) =
1(1x)
m
mx
.
Bibliography
[1] Abramowitz, M. and Stegun, I. A. (eds.), Handbook of Mathematical Functions with Formulas,
Graphs and Mathematical Tables, Dover, 1972, pp. 555-566.
[2] Zucker, I. J. and Joyce, G. S. Special Values of the Hypergeometric Series II., Math. Proc. Cam-
bridge Philos. Soc. 131 (2001) 309-319.
[3] See also http://mathworld.wolfram.com/HypergeometricFunction.html
144 Additional Project Descriptions
Chapter 5
References
Bibliography
1. Martin Golubitsky & Michael Dellnitz, Linear Algebra and Dierential Equations Using MATLAB,
Brooks/Cole Publishing Company, 1999. ISBN 0-534-35425-4
2. Paul Bugl, Explorations in Dierential Equations Using MATLAB, companion manual to Dier-
ential Equations: Matrices and Models, Prentice Hall, 1995. ISBN 0-13-374760-3
3. Kevin R. Coombes, Brian R. Hunt, Ronald L. Lipsman, John E. Osborn & Garrett J. Stuck,
Dierential Equations with MATLAB, John Wiley & Sons, Inc., 2000. ISBN 0-471-32227-X
4. Paul Davis, Dierential Equations: Modelling with MATLAB, Prentice Hall, 1999. ISBN 0-13-
736539-X
5. DELab GUI at http://users.wpi.edu/pwdavis/DELab/ (requires Symbolic Math Toolbox)
6. R. Kent Nagle, Edward B. Sa & Arthur David Snider, Fundamentals of Dierential Equations,
6/E, Addison-Wesley, 2004. ISBN: 0-321-14572-0
7. John C. Polking & David Arnold, Ordinary Dierential Equations Using MATLAB, 2e, Prentice
Hall, 1999. ISBN 0-13-011381-6
8. DFIELD and PPLANE java at http://www.prenhall.com/divisions/esm/app/ode/. See
also http://math.rice.edu/dfield.
9. MATLAB and SIMULINK les described in this manual are available at
http://math.asu.edu/bdw/PUBLIC
General texts on MATLAB
1. Duane Hanselman and Bruce R. Littleeld, Mastering MATLAB 6, Prentice Hall, 2000. ISBN
0-13-019468-9
2. Edward B. Magrab, Shapour Azarm, Balakumar Balachandran, James Duncan, Keith Herold and
Gregory Walsh, An Engineers Guide to MATLAB, Prentice Hall, 2000. ISBN 0-13-011335-2
3. Peter Linz and Richard L. C. Wang, Exploring Numerical Methods: An Introduction to Scientic
Computing Using MATLAB, Jones and Bartlett Publishers, 2003. ISBN 0-7637-1499-2
4. William J. Palm III, Introduction to MATLAB 6 for Engineers: with 6.5 Update, McGraw-Hill,
2001. ISBN 0-07-283300-9
5. Rudra Pratap, Getting Started with MATLAB: A Quick Introduction for Scientists and Engineers,
Oxford University Press, 2002. ISBN 0-19-515014-7
145
146 References
Appendix: MATLAB Quick Reference
Below is presented a quick reference help for essential MATLAB commands in the Ordinary Dierential
Equations context. A wealth of information and examples is also available using the Help > Matlab
help menu or at the web site
http://www.mathworks.com
At this site links can be found to other sites, books, and products dealing with MATLAB, SIMULINK,
and applications to various elds of Mathematics and Science.
1. General Commands
Command Description Example
exit or quit terminate MATLAB session
help display m-le help in Command Window help ode45
= assign value x=2
; return, cancel output x=2;
, separator x=2, y=4; (only x is output)
... line continuation y=x ...
+2;
% comment theta=45; % angle
pause halt execution temporarily pause, pause(2)
ans most recent answer x=2; 2*ans, x=3; 2*ans
2. Mathematical Constants, Operations, and Functions
Command Description Example
+,-,*,/,^ add, subtract, multiply, divide, power x=2; (2/3)*(x+2)^3-10
Inf, NaN innity , Not-a-Number (output) 1/0, 0/0
pi, exp(1), i constants , e,
1 exp(1)^(i*pi), exp(i*pi)
NOTE: if i has been used oth-
erwise (e.g. as loop index) use
sqrt(-1) instead
cos, sin, tan,
cot, sec, csc
trigonometric functions sin(pi/3)-sec(x^2)
acos, asin, atan,
acot, asec, acsc
inverse trigonometric functions acos(0.6)
sqrt square root sqrt(42)
exp exponential exp(2)
log natural logarithm log(exp(1))
log10 logarithm base 10 log10(100)
abs absolute value abs(-3)
conj Complex conjugate conj(2+3*i)
real, imag real, imaginary part z=2+3*i; real(z), imag(z)
round round to nearest integer round(3.7)
inline construct a function f=inline(exp(-t),t)
eval interpret MATLAB strings eval(cos(pi))
feval function evaluation feval(f,3) same as f(3)
function construct an m-le function function gv=g(t)
gv=exp(-t)
@ m-le function handle feval(@g,3)
References 147
3. Array Creation and Manipulation
Command Description Example
[, ] array denition x=[1,2,3]
string concatenation str=[x = num2str(x)]
, (comma) ; column, row separators A=[1,2;3,4;5,6]
: (colon) regularly spaced vector
index into array
rearrange
x=1:2:9
A(2:3,:)
x(:)
transpose x
linspace linearly spaced vectors linspace(1,9,5)
logspace logarithmically spaced vectors logspace(-5,0,6)
eye identity matrix eye(5,5)
zeros array of all zeros zeros(5,3)
ones array of all ones ones(5,3)
rand uniformly distributed random numbers rand, rand(10,1)
randn normally distributed random numbers randn, randn(10,1)
magic magic square magic(4)
save save variable to le save data.mat x A
load retrieve variables from le load data.mat x A
length length of vector length(x)
size array dimensions size(x), size(A)
end last index in array x(end), A(end,1)
.*,./,.^ entry-wise multiply, divide, power x=[1,2,3]; y=1:3;
x.^2.*y./(1+x)
min, max minimum, maximum elements of an array min(x), max(max(A))
sort sort elements in ascending order y=sort(x)
find nd indices and values of nonzero elements i=find(x), [i,j]=find(A)
sum sum of array elements (along rst direction) sum(1:10), sum(A)
cumsum cumulative sum cumsum(1:10)
mean average or mean value of arrays mean(x)
prod product of array elements prod(x)
4. General Display, Evaluation
Command Description Example
clc clear Command Window clc
format display format for output format compact
diary save MATLAB session to le diary session1
disp, display text or array disp(Having fun?)
disp([x= num2str(x)])
int2str integer to string conversion disp([i= int2str(i)])
num2str number to string conversion disp([x= num2str(x)])
tic
...
toc
stopwatch timer tic
[t,y]=ode45(@f,[0,20],1);
toc
input user input N = input(How many? N = )
str = input(Name ? = ,s)
figure create/raise gure window figure(2)
subplot create axes in tiled positions subplot(2,1,2)
plot plot vectors or matrices plot(t,y,r-)
plot3 plot lines and points in 3D plot3(x,y,z,r-)
148 References
Command Description Example
semilogx
semilogy
semi-log scale plot semilogy(t,y,r-)
NOTE: negative values are ignored
meshgrid generate arrays for 3D plots [X,Y]=meshgrid(0:.1:1,0:.1:2)
surf 3-D shaded surface graph surf(X,Y,Z)
contour contour (level curves) plot contour(X,Y,Z)
quiver
quiver3
2D/3D quiver (or velocity) plot quiver(X,Y,dX,dY)
drawnow complete pending drawing drawnow
axis axis scaling axis equal, axis([0,1,0,2])
xlim
ylim
zlim
set/get current x, y, z-axis limits xlim([0,2]), xlim
grid grid lines for plots grid on, grid off
legend add legend legend(f(x),g(x))
xlabel
ylabel
zlabel
x, y, z-axis labels xlabel(time t)
title plot title title(IVP solution)
text add text to graph text(1,2,f(x))
gtext add text to 2D graph with mouse gtext(f(x))
print print graph to le print -depsc out.eps
5. Logical Operations and Control Flow
Command Description Example
==, =, <, <=, >, >=
&, |,
comparison
logical AND, OR, NOT
if x>=2 & y=0
z=sqrt(x-2)/y;
end
any, all test for any/all nonzeros any([0,1,2])
for ...
...
end
repeat statements for i=2:10
x(i)=x(i-1)+1;
end
while ...
...
end
indenitely repeat statements while e<tol
x(i)=x(i-1)+1; e=max(x);
end
if ...
...
elseif ...
...
else
...
end
conditionally execute statements if x==0
y=1;
elseif x==pi
y=-1;
else
y=pi*sin(x)/(x*(x-pi));
end
switch ...
case ...
...
case ...
...
otherwise
...
end
switch among cases switch x
case 0
y=1;
case pi
y=-1;
otherwise
y=pi*sin(x)/(x*(x-pi));
end
break terminate current execution break
continue pass control to next iteration continue
return return to invoking function return
References 149
6. Algebra, Calculus, and Dierential Equations
Command Description Example
interp1 1D data interpolation y = interp1(xdata,ydata,x)
quad/quadl adaptive quadrature quad(1./(1+x.^2),0,2)
fminsearch minimize function fminsearch((x-1).^3,0)
fzero nd zero of 1D function fzero((x-1).^2,0)
NOTE: needs sign change
odeset set IVP solver options odeset(RelTol,1e-6,AbsTol,1e-6);
ode23
ode45
ode15s
ode23s
ode23t
IVP solver [t,y]=ode45(@f,[0,20],y0);
[t,y]=ode45(@f,[0,20],y0,[],param);
[t,y]=ode45(@f,[0,20],y0,options,param);
roots polynomial roots roots([1,4,3])
poly polynomial given roots
characteristic polynomial
poly([-1,-3])
poly(A)
det matrix determinant det(A)
eig eigenvalues, eigenvectors [X,D]=eig(A)
ev=eig(A)
trace sum of diagonal elements trace([1,2;3,4])
norm vector and matrix norms norm(A)
null null space of a matrix null(A)
expm matrix exponential expm(A)
NOTE: do not confuse with exp(A)
system solve Ab
7. SIMULINK Blocks
Block Name Symbol Library
Integrator Continuous
State-Space Continuous
Transfer Fcn Continuous
Fcn Functions
Gain Math
Product Math
Slider Gain Math
Sum Math
Mux, Demux Signals & Systems
Scope Sinks
XY-Graph Sinks
Constant Source
Sine Wave Source