You are on page 1of 155

MATLAB

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

are registered trademarks of The MathWorks, Inc.


MAPLE

is a registered trademark of Waterloo Maple, Inc.


c _2003 B. Welfert
ii
Contents
Preface v
1 Introduction to MATLAB 1
The MATLAB Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Basics and Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Plotting with MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Scripts and Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Matrices and Linear Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
MATLAB Programming and Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2 Ordinary Dierential Equations
with MATLAB 19
Numerical Dierentiation and Solution of the IVP . . . . . . . . . . . . . . . . . . . . . . . . . 19
Direction Fields and Graphical Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
First-Order Scalar IVP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Basic ode45 Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Error Plot, Improving the Accuracy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Parameter-Dependent ODE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Higher-Order and Systems of IVPs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3 MATLAB sessions 35
Laboratory 1: First-Order Dierential Equations, Graphical Analysis . . . . . . . . . . . . . . . 38
Direction elds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Additional Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Laboratory 2: Numerical Solutions (Euler, Improved Euler) for Scalar Equations . . . . . . . . 42
Eulers Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Improved Eulers Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Additional Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Laboratory 3: Solution Sensitivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Dependence of IVP Solution on IC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Existence and Uniqueness . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
Additional Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Laboratory 4: Picard Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Picard iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Numerical Picard Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
Additional problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Laboratory 5: Applications of First-Order Dierential Equations . . . . . . . . . . . . . . . . . 61
Population Growth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Other Models, Parameter Estimation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Laboratory 6: Further Applications of First-Order Dierential Equations . . . . . . . . . . . . 66
iii
The Snowplow Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Aircraft Guidance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Heating and Cooling of Buildings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Laboratory 7: Implementing Higher-Order Dierential Equations . . . . . . . . . . . . . . . . . 72
Reducing a Higher-Order ODE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
MATLAB Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
Additional Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Laboratory 8: The Mass-Spring System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Mass-Spring System without Damping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Mass-Spring System with Damping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
The GUI spring.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Laboratory 9: The Pendulum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
The Undamped Case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
The Linearized Case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
With Damping Present . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
The Poe pendulum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
Laboratory 10: Forced Equations and Resonance . . . . . . . . . . . . . . . . . . . . . . . . . . 89
The Amplitude of Forced Oscillations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
Resonance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
Beats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
Additional Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
Laboratory 11: Analytical and Graphical Analysis of Systems . . . . . . . . . . . . . . . . . . . 94
An Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
Multiple Eigenvalue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Complex Eigenvalues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Additional Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
Laboratory 12: Additional Numerical Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . 102
Taylor and Runge-Kutta Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
Application to a System of ODEs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
Additional Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
Laboratory 13: Introduction to SIMULINK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
An Example SIMULINK Model: spring1.mdl . . . . . . . . . . . . . . . . . . . . . . . . 107
Building a Mass-Spring SIMULINK Model . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Alternate SIMULINK Implementations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
Laboratory 14: Laplace transform, application to linear IVPs . . . . . . . . . . . . . . . . . . . 114
Laplace transform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
Inverse Laplace transform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
Applications to the solution of IVPs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
4 Additional Project Descriptions 127
Note to the Instructor: Group Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
P1. Design your Own Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
P2. The ODE of World-Class Sprint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
P3. Consecutive Reactions for Batch Reactors . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
P4. Normal T-Cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
P5. T-Cells in the Presence of HIV . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
P6. Design of an Electrical Network . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
P7. The Dynamics of Love . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
P8. Hypergeometric Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
5 References 145
Bibliography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
Appendix: MATLAB Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
iv
Preface
This manual is designed to accompany the new edition of Fundamentals of Dierential Equations (and
Boundary Value Problems) by Nagle, Sa and Snider and its format was mostly inspired by the com-
panion Maple Technology Manual written by Kenneth Pothoven. The usefulness of this manual should
however extend well beyond this specic association.
MATLAB is a high-performance language for technical computing which now integrates computa-
tion, visualization, and programming in an easy-to-use environment where problems and solutions are
expressed in familiar mathematical notation (excerpt from The MathWorks website). MATLAB stands
for MATrix LABoratory and was originally written to provide easy access to matrix software developed
by the LINPACK and EISPACK projects.
MATLAB has become a standard instructional tool for introductory and advanced courses in Math-
ematics, Engineering, and Science. In industry, MATLAB is now the tool of choice for high-productivity
research, development, and analysis. This manual explores the use of MATLAB in solving dierential
equations and visualizing and interpreting their solutions. The main objectives are:
1. familiarize students with basic MATLAB programming to solve dierential equations of varying
complexity,
2. provide a platform for testing and experimenting with fundamental aspects of numerical compu-
tations of solutions of dierential equations, and
3. present simple ways to visualize the numerical solutions.
The use of the MATLAB Symbolic Toolbox was limited to short examples with the functions laplace
and ilaplace in Laboratory 14. Custom functions which do not use this toolbox were used to illustrate
the numerical evaluation of these transforms. An introduction to SIMULINK is given in Laboratory
13. SIMULINK provides a tool for building and testing models using the power of MATLAB without
requiring the specic knowledge of the MATLAB language necessary to implement these models.
The versions of MATLAB and SIMULINK used are MATLAB 6.0 and SIMULINK 4, respectively
(Release 12). Changes made in Release 13 (the last available as of June 2003) have no bearing on the
content of this manual.
This manual includes two introductory chapters on MATLAB: the rst one shows how to start
MATLAB and how to use and organize basic commands. It explains in particular how to save groups
of commands in a le, which is important in creating programs that implement a whole problem. The
second chapter is more specic to dierential equations. It goes over how to implement initial value
problems and how to visualize the solution(s), using complete examples. Students are encouraged to
read these two chapters and execute the listed commands before moving to the laboratory section.
Following is the main part of this manual which comprises 14 laboratory sessions covering general
numerical implementation and execution issues when solving dierential equations. This is done in
the context of specic applications, many of which are similar to the ones presented in the MAPLE
companion manual. As noted there, these laboratory sessions vary in length and diculty, and are
included to demonstrate the use of MATLAB as well as to involve students through exploratory exercises.
Instructors should feel free to modify the sessions at their own discretion.
Additional project ideas are included in the last chapter. These projects represent dierent kinds
of applications from various disciplines including chemical, civil, electrical, and mechanical engineering,
including most of the projects ideas (sometimes radically changed though) from the Maple companion
v
book by K. Pothoven. A project idea coming from an actual project carried out in a Dierential
Equations with MATLAB course I have been teaching is also included. Each project is briey described
at the beginning of the chapter.
As always when using a computer software the user should be careful to respect the correct syntax
needed for proper execution. In my experience this represents the most signicant hurdle for students
without any background in computer programming. This manual is designed to help in this regard, by
including simple examples and templates that students can conveniently use as a starting point for their
own applications. Ultimately, some eort must however be made by the student in order to assimilate the
proper ways of using MATLAB by practicing with the examples included in this manual and adapting
them to new problems.
The manuscript was prepared using the L
A
T
E
X document preparation system. PostScript gures
were created using MATLAB or converted from screen capture in Jpeg format using jpeg2ps 1.9 by
Thomas Herz. The cover picture was created from the original book cover of the new (sixth) edition of the
Nagle, Sa and Snider text with a mask based on the MATLAB logo using PhotoShop. The MATLAB
graphical user interfaces dfield6.m and pplane6.m by John Polking and David Arnold were briey used
in this manual. A detailed description is available in their book Ordinary Dierential Equations Using
MATLAB. Many of the MATLAB and SIMULINK programs used in this manual are available online at
http://math.asu.edu/bdw/PUBLIC. Partial funding for this work was provided by a grant to improve
undergraduate education from the College of Liberal Arts and Sciences at Arizona State University.
Bruno Welfert
Arizona State University
September 2003
vi
Chapter 1
Introduction to MATLAB
MATLAB is a computer software commonly used in both education and industry to solve a wide range
of problems.
This chapter provides a brief introduction to MATLAB, and the tools and functions that help you
to work with MATLAB variables and les.
The MATLAB Environment
To start MATLAB double-click on the MATLAB shortcut icon or type matlab & at the
prompt (Unix). The MATLAB desktop opens.
On the right side of the desktop you nd the Command Window, where commands are entered at
the prompt >>.
On the left side you will generally nd the Launch Pad and Workspace windows, and the Command
History and Current Directory windows. For all practical purposes we have in mind I recommend closing
the Launch Pad, Workspace, and Command History windows, if opened. It is convenient to keep the
Current Directory window opened to check for les you create and use in the Command Window.
Note that windows within the MATLAB desktop can be resized by dragging the separator bar(s). A
typical MATLAB desktop is shown in Fig. 1.1.
To exit MATLAB do one of the following:
Click on the close box at the top right of the MATLAB Desktop.
Select File > Exit from the desktop File menu.
Type quit or exit at the Command Window prompt >>.
Basics And Help
Commands are entered in the Command Window.
Basic operations are +, -, *, and /. The sequence
>> a=2; b=3; a+b, a*b,
ans =
5
ans =
1
2 Introduction to MATLAB
Figure 1.1: A typical MATLAB desktop
6
denes variables a and b and assigns values 2 and 3, respectively, then computes the sum a+b and product
ab. Each command ends with , (output is visible) or ; (output is suppressed). The last command on a
line does not require a ,.
Standard functions can be invoked using their usual mathematical notations. For example
>> theta=pi/5;
>> cos(theta)^2+sin(theta)^2
ans =
1
veries the trigonometric identity sin
2
+cos
2
= 1 for =

5
. A list of elementary math functions can
be obtained by typing help elfun in the Command window:
>> help elfun
Elementary math functions.
Introduction to MATLAB 3
Trigonometric.
sin - Sine.
sinh - Hyperbolic sine.
asin - Inverse sine.
asinh - Inverse hyperbolic sine.
cos - Cosine.
cosh - Hyperbolic cosine.
acos - Inverse cosine.
acosh - Inverse hyperbolic cosine.
tan - Tangent.
tanh - Hyperbolic tangent.
atan - Inverse tangent.
atan2 - Four quadrant inverse tangent.
atanh - Inverse hyperbolic tangent.
sec - Secant.
sech - Hyperbolic secant.
asec - Inverse secant.
asech - Inverse hyperbolic secant.
csc - Cosecant.
csch - Hyperbolic cosecant.
acsc - Inverse cosecant.
acsch - Inverse hyperbolic cosecant.
cot - Cotangent.
coth - Hyperbolic cotangent.
acot - Inverse cotangent.
acoth - Inverse hyperbolic cotangent.
Exponential.
exp - Exponential.
log - Natural logarithm.
log10 - Common (base 10) logarithm.
log2 - Base 2 logarithm and dissect floating point number.
pow2 - Base 2 power and scale floating point number.
sqrt - Square root.
nextpow2 - Next higher power of 2.
Complex.
abs - Absolute value.
angle - Phase angle.
complex - Construct complex data from real and imaginary parts.
conj - Complex conjugate.
imag - Complex imaginary part.
real - Complex real part.
unwrap - Unwrap phase angle.
isreal - True for real array.
cplxpair - Sort numbers into complex conjugate pairs.
Rounding and remainder.
fix - Round towards zero.
floor - Round towards minus infinity.
ceil - Round towards plus infinity.
round - Round towards nearest integer.
mod - Modulus (signed remainder after division).
4 Introduction to MATLAB
rem - Remainder after division.
sign - Signum.
To obtain a description of the use of a particular function type help followed by the name of the
function. For example
>> help cosh
COSH Hyperbolic cosine.
COSH(X) is the hyperbolic cosine of the elements of X.
To get a list of other groups of MATLAB programs already available enter help:
>> help
HELP topics:
matlab\general - General purpose commands.
matlab\ops - Operators and special characters.
matlab\lang - Programming language constructs.
matlab\elmat - Elementary matrices and matrix manipulation.
matlab\elfun - Elementary math functions.
matlab\specfun - Specialized math functions.
matlab\matfun - Matrix functions - numerical linear algebra.
matlab\datafun - Data analysis and Fourier transforms.
matlab\audio - Audio support.
matlab\polyfun - Interpolation and polynomials.
matlab\funfun - Function functions and ODE solvers.
matlab\sparfun - Sparse matrices.
matlab\graph2d - Two dimensional graphs.
matlab\graph3d - Three dimensional graphs.
matlab\specgraph - Specialized graphs.
matlab\graphics - Handle Graphics.
matlab\uitools - Graphical user interface tools.
matlab\strfun - Character strings.
matlab\iofun - File input/output.
matlab\timefun - Time and dates.
matlab\datatypes - Data types and structures.
matlab\verctrl - Version control.
matlab\winfun - Windows Operating System Interface Files (DDE/ActiveX)
matlab\demos - Examples and demonstrations.
toolbox\local - Preferences.
matlabR12\work - (No table of contents file)
For more help on directory/topic, type "help topic".
Another way to obtain help is through the desktop Help menu, Help > MATLAB Help, or by
connecting to the Mathworks web site at www.mathworks.com.
MATLAB is case-sensitive. For example
>> theta=1e-3, Theta=2e-5; ratio=theta/Theta
theta =
Introduction to MATLAB 5
0.0010
Theta =
2.0000e-005
ratio =
50
The quantities Inf () and NaN (Not a Number) also appear frequently. Compare
>> c=1/0
Warning: Divide by zero.
c =
Inf
with
>> d=0/0
Warning: Divide by zero.
d =
NaN
Plotting with MATLAB
To plot a function you have to create two arrays (vectors): one containing the abscissae, the other the
corresponding function values. Both arrays should have the same length. For example, consider plotting
the function
y = f(x) =
x
2
sin(x) +e
x
x 1
for 0 x 2. First choose a sample of x values in this interval:
>> x=[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1, ...
1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2]
x =
Columns 1 through 4
0 0.1000 0.2000 0.3000
Columns 5 through 8
0.4000 0.5000 0.6000 0.7000
Columns 9 through 12
6 Introduction to MATLAB
0.8000 0.9000 1.0000 1.1000
Columns 13 through 16
1.2000 1.3000 1.4000 1.5000
Columns 17 through 20
1.6000 1.7000 1.8000 1.9000
Column 21
2.0000
or simply
>> x=0:.1:2
x =
Columns 1 through 4
0 0.1000 0.2000 0.3000
Columns 5 through 8
0.4000 0.5000 0.6000 0.7000
Columns 9 through 12
0.8000 0.9000 1.0000 1.1000
Columns 13 through 16
1.2000 1.3000 1.4000 1.5000
Columns 17 through 20
1.6000 1.7000 1.8000 1.9000
Column 21
2.0000
Try also
>> x=linspace(0,2,21)
x =
Columns 1 through 4
0 0.1000 0.2000 0.3000
Introduction to MATLAB 7
Columns 5 through 8
0.4000 0.5000 0.6000 0.7000
Columns 9 through 12
0.8000 0.9000 1.0000 1.1000
Columns 13 through 16
1.2000 1.3000 1.4000 1.5000
Columns 17 through 20
1.6000 1.7000 1.8000 1.9000
Column 21
2.0000
Note that an ellipsis ... was used to continue a command too long to t in a single line.
The output for x can be suppressed (by adding ; at the end of the command) or condensed by entering
format compact:
>> format compact
>> x
Columns 1 through 4
0 0.1000 0.2000 0.3000
Columns 5 through 8
0.4000 0.5000 0.6000 0.7000
Columns 9 through 12
0.8000 0.9000 1.0000 1.1000
Columns 13 through 16
1.2000 1.3000 1.4000 1.5000
Columns 17 through 20
1.6000 1.7000 1.8000 1.9000
Column 21
2.0000
From now on we shall use such format for all output.
To evaluate the function f simultaneously at all the values contained in x, type
>> y=(x.^2-sin(pi.*x)+exp(x))./(x-1)
Warning: Divide by zero.
y =
Columns 1 through 4
-1.0000 -0.8957 -0.8420 -0.9012
Columns 5 through 8
-1.1679 -1.7974 -3.0777 -5.6491
Columns 9 through 12
-11.3888 -29.6059 Inf 45.2318
Columns 13 through 16
26.7395 20.5610 17.4156 15.4634
Columns 17 through 20
8 Introduction to MATLAB
14.1068 13.1042 12.3468 11.7832
Column 21
11.3891
Note that the function becomes innite at x = 1 (vertical asymptote). The array y inherits the dimension
of x, namely 1 (row) by 21 (columns). Note also the use of parentheses.
IMPORTANT REMARK
In the above example *, / and ^ are preceded by a dot . in order for the expression to be evaluated for
each component (entry) of x. This is necessary to prevent MATLAB from interpreting these symbols
as standard linear algebra symbols operating on arrays. Because the standard + and - operations on
arrays already work componentwise, a dot is not necessary for + and -.
The command
>> plot(x,y)
creates a Figure window and shows the function, see Fig. 1.2. The gure can be edited and manipulated
using the Figure window menus and buttons. Alternately, properties of the gure can also be dened
directly at the command line:
>> x=0:.01:2;
>> y=(x.^2-sin(pi.*x)+exp(x))./(x-1);
>> plot(x,y,r-,LineWidth,2);
>> axis([0,2,-10,20]); grid on;
>> title(f(x)=(x^2-sin(\pi x)+e^x)/(x-1));
>> xlabel(x); ylabel(y);
Introduction to MATLAB 9
Figure 1.2: A Figure window
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
10
5
0
5
10
15
20
x
y
f(x)=(x
2
sin( x)+e
x
)/(x1)
Figure 1.3: The function y = f(x) =
x
2
sin(x)+e
x
x1
.
10 Introduction to MATLAB
The number of x-values has been increased for a smoother curve (what is the new size of x?). The
curve now appears wider and in red. The range of x and y values has been reset (always a good idea
in the presence of vertical asymptotes). A title and labels have been added. The resulting new plot is
shown in Fig. 1.3. For more options type help plot in the Command Window.
Scripts and Functions
Files containing MATLAB commands are called m-les and have a .m extension. They are two types:
1. A script is simply a collection of MATLAB commands gathered in a single le. The value of the
data created in a script is still available in the Command Window after execution.
2. A function is similar to a script, but can accept and return arguments. Unless otherwise specied
any variable inside a function is local to the function and not available in the Workspace. A
function invariably starts with the command
function output = function_name(input)
and should contain one or several commands dening the output.
Use a function when a group of commands needs to be evaluated multiple times.
To create a new script or function select the MATLAB desktop File menu File > New > M-le.
In the MATLAB text editor window enter the commands as you would in the Command window. To
save the le use the menu File > Save or File > Save As..., or the shortcut Save button .
Figure 1.4: The script myplot.m in the MATLAB Editor window.
Examples of script/function:
1. script
myplot.m myplot.m (see Fig. 1.4).
Introduction to MATLAB 11
x=0:.01:2; % x-values
y=(x.^2-sin(pi.*x)+exp(x))./(x-1); % y-values
plot(x,y,r-,LineWidth,2); % plot in red
axis([0,2,-10,20]); grid on; % set range and add grid
title(f(x)=(x^2-sin(\pi x)+e^x)/(x-1)); % add title
xlabel(x); ylabel(y); % add labels
2. script+function (two separate les)
myplot2.m (driver script)
x=0:.01:2; % x-values
y=feval(@myfunction,x); % evaluate myfunction at x
plot(x,y,r-,LineWidth,2); % plot in red
axis([0,2,-10,20]); grid on; % set range and add grid
title(f(x)=(x^2-sin(\pi x)+e^x)/(x-1)); % add title
xlabel(x); ylabel(y); % add labels
myfunction.m (function)
function y=myfunction(x) % defines function
y=(x.^2-sin(pi.*x)+exp(x))./(x-1); % y-values
3. script+function (one single le)
myplot1.m (driver script converted to function + function)
function myplot1
x=0:.01:2; % x-values
y=feval(@myfunction,x); % evaluate myfunction at x
plot(x,y,r-,LineWidth,2); % plot in red
axis([0,2,-10,20]); grid on; % set range and add grid
title(f(x)=(x^2-sin(\pi x)+e^x)/(x-1)); % add title
xlabel(x); ylabel(y); % add labels
%-----------------------------------------
function y=myfunction(x) % defines function
y=(x.^2-sin(pi.*x)+exp(x))./(x-1); % y-values
In case 2 myfunction.m can be used in any other m-le (just as other predened MATLAB functions).
In case 3 myfunction.m can be used by any other function in the same m-le (myplot1.m) only. Use 3
when dealing with a single project and 2 when a function is used by several projects.
It is convenient to add descriptive comments into the script le. Anything appearing after % on any
given line is understood as a comment (in green in the MATLAB text editor).
To execute a script simply enter its name (without the .m extension) in the Command Window, e.g.,
>> myplot;
in case 1,
>> myplot2;
in case 2 and
>> myplot1;
in case 3 above. The function myfunction can also be used independently if implemented in a separate
le myfunction.m:
12 Introduction to MATLAB
>> x=2; y=myfunction(x)
y =
11.3891
A script can be called from another script or function (in which case it is local to that function).
If any modication is made, the script or function can be re-executed by simply retyping the script
or function name in the Command Window (or use the up-arrow on the keyboard to browse through
past commands).
IMPORTANT REMARK
By default MATLAB saves les in the Current Directory (folder). When entering MATLAB the
Current Directory is the Work Directory (e.g., C:matlabR12work). Make sure the le is saved
where you want it. To change directory use the Current Directory window or the Current Directory
box on top of the MATLAB desktop.
A function le can contain a lot more than a simple evaluation of a function f(x) or f(t, y). But in
simple cases f(x) or f(t, y) can simply be dened using the inline syntax. Compare
>> ...
>> slope = feval(@f,2,1) % note use of @. Try also slope=f(2,1)
slope =
3
where f.m is the le containing
function dydt = f(t,y)
dydt = t^2-y;
to
>> ...
>> f = inline(t^2-y,t,y)
f =
Inline function:
f(t,y) = t^2-y
>> slope = feval(f,2,1) % note no @
slope =
3
However, an inline function is only available where it is used and not to other functions. It is not
recommended when the function implemented is too complicated or involves too many statements.
Matrices and Linear Algebra
We have used one-dimensional 1 21 arrays x and y in previous examples. MATLAB can handle higher
dimensional arrays. Two-dimensional arrays (matrices) are commonly used in many situations.
Matrices can be constructed in MATLAB in dierent ways. For example the 3 3 matrix A =
_
_
8 1 6
3 5 7
4 9 2
_
_
can be entered as
>> A=[8,1,6;3,5,7;4,9,2]
A =
8 1 6
3 5 7
4 9 2
or
Introduction to MATLAB 13
>> A=[8,1,6;
3,5,7;
4,9,2]
A =
8 1 6
3 5 7
4 9 2
or dened as the concatenation of 3 rows
>> row1=[8,1,6]; row2=[3,5,7]; row3=[4,9,2]; A=[row1;row2;row3]
A =
8 1 6
3 5 7
4 9 2
or 3 columns
>> col1=[8;3;4]; col2=[1;5;9]; col3=[6;7;2]; A=[col1,col2,col2]
A =
8 1 6
3 5 7
4 9 2
Note the use of , and ;. Concatenated rows/columns must have the same length. Larger matrices can
be created from smaller ones in the same way:
>> C=[A,A] % Same as C=[A A]
C =
8 1 6 8 1 6
3 5 7 3 5 7
4 9 2 4 9 2
The matrix C has dimension 3 6 (3 by 6). On the other hand smaller matrices (submatrices) can
be extracted from any given matrix:
>> A(2,3) % coefficient of A in 2nd row, 3rd column
ans =
7
>> A(1,:) % 1st row of A
ans =
8 1 6
>> A(:,3) % 3rd column of A
ans =
6
7
2
>> A([1,3],[2,3]) % keep coefficients in rows 1 & 3 and columns 2 & 3
ans =
1 6
9 2
Some matrices are already predened in MATLAB:
>> I=eye(3) % the Identity matrix
I =
1 0 0
0 1 0
14 Introduction to MATLAB
0 0 1
>> magic(3)
ans =
8 1 6
3 5 7
4 9 2
(what is magic about this matrix?)
Matrices can be manipulated very easily in MATLAB (unlike Maple). Here are sample commands
to exercise with:
>> A=magic(3);
>> B=A % transpose of A, i.e, rows of B are columns of A
B =
8 3 4
1 5 9
6 7 2
>> A+B % sum of A and B
ans =
16 4 10
4 10 16
10 16 4
>> A*B % standard linear algebra matrix multiplication
ans =
101 71 53
71 83 71
53 71 101
>> A.*B % coefficientwise multiplication
ans =
64 3 24
3 25 63
24 63 4
Try A*A, A^2, A.^2.
Two MATLAB commands are especially relevant when studying the solution of linear systems of
dierentials equations:
1. x=Ab determines the solution x = A
1
b of the linear system Ax = b. The array b must have as
many rows as the matrix A.
2. [S,D]=eig(A) determines the eigenvectors of A (columns of S) and associated eigenvalues (diagonal
coecients of D) (note that the eig function has one input and two output arguments).
As an example consider the matrix A =magic(3) again and x =
_
_
1
2
3
_
_
:
>> A=magic(3)
A =
8 1 6
3 5 7
4 9 2
>> x=[1,2,3] % same as x=[1;2;3]
x =
1
2
3
Introduction to MATLAB 15
>> b=A*x
b =
28
34
28
>> A\b % this is x!
ans =
1
2
3
>> inv(A)*b % less efficient and accurate
ans =
1.0000
2.0000
3.0000
>> [S,D]=eig(A)
S =
-0.5774 -0.8131 -0.3416
-0.5774 0.4714 -0.4714
-0.5774 0.3416 0.8131
D =
15.0000 0 0
0 4.8990 0
0 0 -4.8990
>> A*S(:,1)-D(1,1)*S(:,1) % test 1st eigenvector-eigenvalue pair
ans =
1.0e-014 *
-0.1776
0.3553
-0.3553
Note the multiplicative factor 10
14
in the last computation. MATLAB performs all operations using
standard IEEE double precision.
MATLAB Programming and Debugging
Several constructs are used in MATLAB:
1. repetitive loops (xed number of times)
for <expression>
<list of commands>
end
2. repetitive loops (indenite number of times)
while <expression>
<list of commands>
end
3. conditional branching
if expression
16 Introduction to MATLAB
<list of commands>
elseif expression
<list of commands>
:
else
<list of commands>
end
or
switch expression
case <expression>
<list of commands>
:
case <expression>
<list of commands>
otherwise
<list of commands>
end
The following examples illustrate the use of each construct:
1. for loop: determine the sum of the squares of integers from 1 to 10
S = 0; % initialize running sum
for k = 1:10
S = S+k^2;
end
What is S? Verify with MATLAB.
2. while loop: determine the sum of the inverses of squares of integers from 1 until the inverse of the
integer square is less than 10
5
S = 0; % initialize running sum
k = 1; % initialize current integer
incr = 1; % initialize test value
while incr>=1e-10
S = S+incr;
k = k+1;
incr = 1/k^2;
end
What is the value of S returned by this script? Compare to

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 rhs (= f(t, y) = t


2
y). Better accuracy
is obtained for smaller h.
19
20 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.1: Numerical comparison between of 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

varies in a wide range a better perception of the


direction of the eld is obtained by scaling all arrows such that they have the same length (normalization):
>> N=sqrt(dT.^2+dY.^2); % magnitude of arrows
>> dT=dT./N; % normalize arrows to get all same length
>> dY=dY./N;
>> quiver(T,Y,dT,dY) % draw arrows (t,y) --> (t+dt,y+dy)
>> axis equal
>> axis([-4 4 -4 4]) % repeat adjustments...
>> grid on
>> print -depsc dfieldb.eps % export new plot
It may be convenient to create a function le which can be reused for dierent ODEs... This is left for
Laboratory 1 page 114.
Approximate verication that a given function is solution of a particular ODE can also be done by
simply superposing the function to the direction eld. After the previous script add
>> hold on
y=t.^2-2*t+2+C*exp(-t);
plot(t,y,r,LineWidth,2);
hold off
See Fig. 2.3.
Ordinary Dierential Equations with MATLAB 21
4 3 2 1 0 1 2 3 4
4
3
2
1
0
1
2
3
4
4 3 2 1 0 1 2 3 4
4
3
2
1
0
1
2
3
4
Figure 2.2: Direction eld for 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

= 1 siny and sample solutions using DFIELD6


2. Consider the dierential equation
dy
dt
= y

= y(y + 1)(y 2). (L1.2)


(a) Examine the direction eld in the window 0 t 5, 2 y 4 using dirfield.m. What
is the limit of y(t) as t if y(0) = 1.9? If y(0) = 2.1?
(b) Use the GUI dfield6.m to draw various representative solutions. Do any of the solution
curves ever cross each other? Do you know why? (see Theorem 1 in 1.2 of the text by Nagle,
Sa, and Snider.)
(c) If y(0) =
1
2
can y eventually be 1? Why?
3. Use dirfield.m AND dfield6.m to plot the direction eld and some solution curves for each of
the following dierential equations in the window 5 t 5, 5 y 5. In each case determine
whether there exist any equilibrium solutions and characterize the appearance of the solutions.
MATLAB sessions: Laboratory 1 41
(a) 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

= f(t, y) is even if f is an odd function of t (i.e., f(t, y) =


f(t, y)). Use this to nd a few ODEs whose solutions are symmetric with respect to the y-axis.
Verify by plotting the direction eld.
42 MATLAB sessions: Laboratory 2
Laboratory 2
Numerical Solutions by Euler and Improved Euler Methods
(scalar equations)
(1.4 and 3.6 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. Implement Eulers method as well as an improved version to numerically solve an IVP.
2. Compare the accuracy and eciency of the methods with methods readily available in MATLAB.
3. Apply the methods to specic problems and investigate potential pitfalls of the methods.
Eulers Method
To derive Eulers method start from y(t
0
) = y
0
and consider a Taylor expansion at t
1
= t
0
+h:
y(t
1
) = y(t
0
) +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

= f(t, y), y(t


0
) = y
0
can be reformulated as
y(t
1
) = y(t
0
) +
_
t
1
t
0
f(s, y(s))ds. (L2.2)
Then (L2.1) amounts to approximating the integral in (L2.2) using a left point rule.
The iteration (L2.1) is repeated to obtain y
2
y(t
2
), . . . such that
y
n+1
= y
n
+hf(t
n
, y
n
)
t
n+1
= t
n
+h
Geometrically, the approximation made is equivalent to replacing the
solution curve by the tangent line at (t
0
, y
0
). From the gure we have
f(t
0
, y
0
) = f(t
0
, y(t
0
)) = 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

As an example consider the IVP


y

= 2y = f(t, y) with y(0) = 3.


Note that here f does not explicitly depend on t (the ODE is called autonomous), but does implicitly
through y = y(t). To apply Eulers method we start with the initial condition and select a step size h.
Since we are constructing arrays t and y without dimensionalizing them rst it is best to clear these
names in case they have been used already in the same MATLAB work session.
MATLAB sessions: Laboratory 2 43
>> clear t y % no comma between t and y! type help clear for more info
>> y(1)=3; t(1)=0; h=0.1;
Since f is simple enough we may use the inline syntax:
>> f=inline(2*y,t,y)
f =
Inline function:
f(t,y) = 2*y
Note that the initialization y(1)=3 should not be interpreted as the value of y at 1 is 3, but rather
the rst value of y is 3. In other words the 1 in y(1) is an index, not a time value! Unfortunately,
MATLAB indices in arrays must be positive (a legacy from Fortran...). The successive approximations
at increasing values of t are then obtained as follows:
>> y(2)=y(1)+h*f(t(1),y(1)), t(2)=t(1)+h,
y =
3.0000 3.6000
t =
0 0.1000
>> y(3)=y(2)+h*f(t(2),y(2)), t(3)=t(2)+h,
y =
3.0000 3.6000 4.3200
t =
0 0.1000 0.2000
>> y(4)=y(3)+h*f(t(3),y(3)), t(4)=t(3)+h,
y =
3.0000 3.6000 4.3200 5.1840
t =
0 0.1000 0.2000 0.3000
>> y(5)=y(4)+h*f(t(4),y(4)), t(5)=t(4)+h,
y =
Columns 1 through 4
3.0000 3.6000 4.3200 5.1840
Column 5
6.2208
t =
Columns 1 through 4
0 0.1000 0.2000 0.3000
Column 5
0.4000
>> y(6)=y(5)+h*f(t(5),y(5)), t(6)=t(5)+h,
y =
Columns 1 through 4
3.0000 3.6000 4.3200 5.1840
Columns 5 through 6
6.2208 7.4650
t =
Columns 1 through 4
0 0.1000 0.2000 0.3000
Columns 5 through 6
0.4000 0.5000
The arrays y and t are 16 row arrays. The dimension increases as new values of y and t are computed.
Each time a new value if computed the whole array is output. To avoid this the output in each command
can be suppressed (with a ;) and the list of computed y values vs t values can be output at the end only.
To do this we simply concatenate the column versions of t and y into a 6 2 array:
44 MATLAB sessions: Laboratory 2
>> [t(:),y(:)] % same as [t,y] here
ans =
0 3.0000
0.1000 3.6000
0.2000 4.3200
0.3000 5.1840
0.4000 6.2208
0.5000 7.4650
A better way is to plot y vs t:
>> plot(t,y); axis tight;
0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5
3
3.5
4
4.5
5
5.5
6
6.5
7
7.5
0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5
3
3.5
4
4.5
5
5.5
6
6.5
7
7.5
8
Figure L2a: Eulers method applied to y

= 2y, y(0) = 3 with step h = 0.1 (left) and h =


0.5
50
= 0.01
(right).
See Fig. L2a, left. If more steps are required it is more convenient to use a do loop. The following
function implements these ideas.
euler.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 Eulers method with N time steps
% use: euler(f,[tmin,tmax],y0,N) (or @f)
h = (tspan(2)-tspan(1))/N;
t = tspan(1); tout = t;
y = y0(:); yout = y.;
for n=1:N
y = y+h*feval(f,t,y); t = t+h;
yout = [yout; y.]; tout = [tout; t];
end
>> [t,y] = euler(f,[0,.5],3,50); % use @f if defined in separate function
>> [t,y]
ans =
0 3.0000
0.0100 3.0600
0.0200 3.1212
0.0300 3.1836
0.0400 3.2473
MATLAB sessions: Laboratory 2 45
0.0500 3.3122
: :
0.4500 7.3136
0.4600 7.4598
0.4700 7.6090
0.4800 7.7612
0.4900 7.9164
0.5000 8.0748
An even longer output is obtained for larger values of N. Obviously, graphing the approximate solution
using plot(t,y); axis tight; takes less space and is more revealing. The result is shown in Fig. L2a,
right.
Both plots in Fig. L2a look the same but notice the dierence in vertical (y) scale. To compare the
two approximations we plot both approximations on the same gure, together with the exact solution
y(t) = 3e
2t
:
>> [t5,y5] = euler(f,[0,.5],3,5); % use @f if defined in separate function
>> [t50,y50] = euler(f,[0,.5],3,50);
>> t = linspace(0,.5,100); y = 3*exp(2*t);
>> plot(t5,y5,ro-,t50,y50,bx-,t,y,k-); axis tight;
>> legend(Euler N = 5,Euler N = 50,Exact,2);
0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5
3
3.5
4
4.5
5
5.5
6
6.5
7
7.5
8 Euler N = 5
Euler N = 50
Exact
Figure L2b: Eulers method applied to y

= 2y, y(0) = 3 with step h = 0.1 and h = 0.01, compared to


the exact solution.
The function legend adds a legend. Each argument introduces a description of the corresponding curve
from plot. The last argument controls the placement of the legend in the gure. Type help legend
for more details.
IMPORTANT REMARK
When using 5 steps of size h = 0.1 the approximation of the exact value y(0.5) = 3e 8.1548 is stored
in y(6). On the other hand when using 50 intervals of size h = 0.01, it is stored in y(51). To avoid
confusion both can be referenced by y(end).
1. Answer the following questions regarding what you see in Fig L2b.
46 MATLAB sessions: Laboratory 2
(a) What are the exact value at t = 0.5 and the corresponding Euler approximations using 5
and 50 steps? Using the geometric interpretation of Eulers method explain why both Euler
approximations underestimate the exact solution in this particular example.
(b) If the error is dened by e = y(0.5) y(end) compare the error using 50 steps to error
obtained with 5 steps. Which approximation is more accurate? What is the ratio of the two
errors? How does this ratio relate to the ratio of the number of steps used?
(c) Determine the Euler approximations obtained with N = 500 and N = 5000 steps and conrm
your conclusions.
2. Consider the IVP y

= 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, y(0) = 3. Determine the improved 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)? Compare to the results
obtained for Eulers method.
Additional Problems
5. Repeat problems 2 and 4 for 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

= y(3 y), y(0) = 2.


7. A child situated at the point (0, Y
0
) on the positive y-axis is dragging a toy on a string. He begins
pulling the toy initially resting at (x
0
, 0) on the positive x-axis and walks at a constant pace v
away from the origin along the positive y-axis.
48 MATLAB sessions: Laboratory 2
(a) Show that the dierential equation describing the
trajectory followed by the toy is
dy
dx
= 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

= y with y(0) = 1. Lets apply Eulers method to obtain an approximate


solution at t = 2:
>> f=inline(y,t,y)
f =
Inline function:
f(t,y) = y
>> [t,y]=euler(f,[0,2],1,20);
>> [t,y]
ans =
0 1.0000
0.1000 1.1000
0.2000 1.2100
0.3000 1.3310
0.4000 1.4641
0.5000 1.6105
: :
1.5000 4.1772
1.6000 4.5950
1.7000 5.0545
1.8000 5.5599
1.9000 6.1159
2.0000 6.7275
>> newy0=y(end)*exp(-2) % new IC
newy0 =
0.9105
>> [newt,newy]=ode45(f,t,newy0); % "exact" solution with new IC at same t
>> [newt,newy]
ans =
0 0.9105
0.1000 1.0062
0.2000 1.1120
0.3000 1.2290
0.4000 1.3583
0.5000 1.5011
: :
1.5000 4.0804
1.6000 4.5096
1.7000 4.9839
50 MATLAB sessions: Laboratory 3
1.8000 5.5080
1.9000 6.0873
2.0000 6.7275 <--- same value at t=2 as with Euler and original IC
The approximate solution at t = 2 to the IVP can thus be thought of as the exact solution to the same
ODE but with a dierent initial condition. To understand the likelihood of a numerical solution to
deviate from the exact solution it is then reasonable to determine how exact solution curves are modied
when the initial condition is perturbed.
Dependence of the Solution of IVPs on the Initial Condition
To determine the eect of a change y
0
in the initial condition y
0
has on the solution y(t) of 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) = f(t, y(t)) =


f
y
(t, y(t)) y(t) (chain rule).
On the other hand
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

= f(t) (i.e., f does not explicitly depend on y) we have


f
y
= 0 so that the relation (L3.4) becomes y(t) = y
0
. as an example consider the ODE 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

= f(y) (i.e., f does not explicitly depend on t, such


an ODE is called autonomous) regions where f

(y) > 0 are regions where perturbations expand


and regions where f

(y) < 0 are regions where perturbations contract. As an example consider the
ODEs y

= y (f

(y) = 1, expanding solutions) and y

= y (f

(y) = 1, contracting solutions).


The direction eld and several solution curves are shown in Fig. L3a, center and right. The eld
direction is the same for all points situated on the same horizontal line y = cst.
2 1 0 1 2
4
3
2
1
0
1
2
3
4
2 1 0 1 2
4
3
2
1
0
1
2
3
4
2 1 0 1 2
4
3
2
1
0
1
2
3
4
Figure L3a: Direction eld of y

= e
t
(left), y

= y (center), and y

= y (right) with several solution


curves.
In general ODEs exhibit both regions where solutions contract and regions where solutions expand,
as illustrated in the following problems.
1. Consider the ODE 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

y, y(0) = 0? (hint: think of functions which


are dened piecewise).
5. Consider the IVP y

= 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

y with two solutions satisfying y(0) = 0, namely y(t) = 0 and


y(t) = t
2
. Remark: the direction eld has been plotted using a nonlinear spacing in the y-direction to
emphasize its behavior close to the t-axis.
(a) Is the solution guaranteed to exist? Is is unique?
(b) Verify that y(t) = (t +

)
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

= f(y) is called a sink if f

(y
e
) < 0 and
a source if f

(y
e
) > 0.
8. Consider the (autonomous) ODE y

= y cos y = f(y). Examine the plot of f between 2 and 2.


Identify sources and sinks. Verify your nding by plotting the direction eld.
>> y = -2*pi:pi/20:2*pi; plot(y,y.*cos(y));
8 6 4 2 0 2 4 6 8
8
6
4
2
0
2
4
6
8
9. Consider the IVP 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 in (L3.6) and solve for y


n+1
).
(c) Plot the sequence of points (t
n
= nh, y
n
) obtained using the following commands:
y(1) = ??; % complete
t(1) = 0; tf = 2; N = 10; h = (tf-t0)/N;
for n = 1:N
y(n+1) = ??; % complete
t(n+1) = t(n)+h;
end
plot(t,y)
Compare the values obtained with y(t
n
) = t
2
n
(increase N is necessary).
(d) What conclusions can you infer from this problem regarding the ability of implicit vs explicit
methods in obtaining solutions of problems with large
f
y
?
MATLAB sessions: Laboratory 3 55
10. Consider the IVP y

= 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

= g(t) with y(t


0
) = y
0
is equivalent to y(t) = y
0
+
_
t
t
0
g(s) ds. Here g(t) = f(t,
0
(t)).)
The right-hand side of (L4.1) thus denes another approximation to the function y. We call this ap-
proximation
1
, i.e.,

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

= y with y(0) = 1. We set


0
(t) = 1. Then

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

= 2t(y +1), y(0) = 0


and determine to which function they converge. Check your calculation numerically using picard.m
and by solving the IVP analytically.
5. Show that if y(t) = y
0
is a (constant) solution to the IVP y

= f(t, y), y(0) = y


0
, then
n
(t) = y
0
for n > 0 if
0
(t) = y
0
. More generally, show that if y(t) is a (possibly non-constant) solution to
the IVP y

= f(t, y), y(0) = y


0
, then
n
(t) = y(t) for n > 0 if
0
(t) = y(t) (i.e., a solution remains
a solution!)
60 MATLAB sessions: Laboratory 4
6. Consider the IVP 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

is a temperature set by a furnace or air conditioning unit (in degrees


Fahrenheit). We assume that daily variations of the outside air temperature are modelled by
T
out
= 80 15 cos
_
t
12
_
.
The temperature T

is set such that k(

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

T(t)[dt for the rst model and E


2
=
_
48
0
[U[dt
for the second. Which strategy uses the most energy?
72 MATLAB sessions: Laboratory 7
Laboratory 7
Implementing Higher-Order Dierential Equations
(Ch. 4, 6 of the Nagle/Sa/Snider text)
Numerical solution to IVPs involving higher order ODEs homogeneous or not, linear or not, can be
obtained using the same MATLAB commands as in the rst-order by rewriting the ODE in the form of
a system of rst order ODEs.
Our objectives in this laboratory are as follows:
1. Learn how to reduce a higher-order IVP to a rst-order system
2. Learn how to implement a higher-order/system ODE in MATLAB using ode45.m and euler.m.
3. Get some prociency in analyzing and comparing solutions for dierent but similar problems.
Reducing a Higher-Order ODE
(see 5.2, page 243, of the Nagle/Sa/Snider text)
Lets start with an example. Consider the IVP
d
2
y
dt
2
+ 4
dy
dt
+ 3y = cos t, with y(0) = 1,
dy
dt
(0) = 0. (L7.1)
To reduce the order of the ODE we introduce the intermediate unknown function v =
dy
dt
. As a result
dv
dt
=
d
2
y
dt
2
so that the ODE can be written
dv
dt
+ 4v + 3y = t + cos t. This equation only involves rst-
order derivatives, but we now have two unknown functions y = y(t) and v = v(t) with two ODEs. For
MATLAB implementations it is necessary to write these ODEs in the form
d
dt
= . . .. Thus
d
2
y
dt
2
+ 4
dy
dt
+ 3y = cos t
_
dy
dt
= v,
dv
dt
= cos t 4v 3y.
(L7.2)
Initial conditions from (L7.1) must also be transformed into initial conditions for y and v. Simply,
y(0) = 1,
dy
dt
(0) = 0
_
y(0) = 1,
v(0) = 0.
(L7.3)
We are now ready to implement the IVP in MATLAB.
MATLAB Implementation
The following code shows how to solve the IVP (L7.1) for 0 t 12 using the MATLAB routine ode45.
function lab7ex1
t0 = 0; tf = 12; % initial and final times
y0 = -1; v0 = 0; % initial conditions
[t,Y] = ode45(@f,[t0,tf],[y0,v0]);
y = Y(:,1); v = Y(:,2); % extract y and v from output matrix Y
figure(1); plot(t,y,b+-,t,v,ro-); % time series for y and v
legend(y(t),v(t)=y(t)); grid on % note the use of for
figure(2); plot(y,v); % phase plot
xlabel(y); ylabel(v=y); grid on
%------------------------------------
MATLAB sessions: Laboratory 7 73
function dYdt = f(t,Y)
y = Y(1); v = Y(2);
dYdt = [ v ; cos(t)-4*v-3*y ];
Note how the initial conditions are specied in the calling sequence of ode45, in the form of an array
[y0,v0] ([y0;v0] is also valid). The routine ode45 returns a vector t containing the times in the
interval [0, 4] at which the solution was computed, and a matrix Y with two columns of the same length
as t, one for each of y and v (in that order). Note how the approximations for y and v are retrieved
from Y.
The time series for both y and v are plotted in the MATLAB gure window 1, and the phase plot
showing v vs y is done in the gure window 2.
0 2 4 6 8 10 12
1
0.8
0.6
0.4
0.2
0
0.2
0.4
0.6
0.8
y(t)
v(t)=y(t)
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

Figure L7a: Time series y = y(t) and v = v(t) = y

(t) (left), and phase plot v = y

vs. y for (L7.1).


1. (a) For what (approximate) value(s) of t is y reaches a local maximum in the window 0 t 12?
Check by reading the Y matrix.
(b) What seems to be the long term behavior of y?
(c) Modify the initial conditions. Does the long term behavior of the solution change? If yes in
what way?
2. Implement the IVP y

+ 2y

+ y = cos t with y(0) = y

(0) = 0. Plot both time series of y and y

and the phase plot y

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

vs. y (right) obtained from ode45.m and


euler.m for the problem (L7.1).
3. Solve the problem (L7.1) using the improved Euler method from page 47. Compare the results
with those obtained from ode45 and euler.
Nonlinear Problems
Nonlinear problems do not present any additional diculty from an implementation point of view (they
may present new numerical challenges for integration routines like ode45). As an example consider the
modied problem
d
2
y
dt
2
+ 4y
2
dy
dt
+ 3y = cos t, with y(0) = 1,
dy
dt
(0) = 0. (L7.4)
The ODE (L7.4) is very similar to (L7.1) except for the y
2
term in the left-hand side. Because of the
factor y
2
the ODE (L7.4) is nonlinear, while (L7.1) is linear. There is however very little to change
in the implementation of (L7.1) to solve (L7.4). The driver part lab7ex1 is not modied (same initial
conditions) while the ODE denition becomes
function dYdt = f(t,Y)
y = Y(1); v = Y(2);
dYdt = [ v ; cos(t)-4*y^2*v-3*y ];
The new output is shown in Fig L7c.
4. (a) Compare the output of Figs L7a and L7c. Describe the changes in the behavior of the solution
in the short term.
MATLAB sessions: Laboratory 7 75
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)
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
y
v
=
y

Figure L7c: Time series y = y(t) and v = v(t) = y

(t) (left), and phase plot v = y

vs. y for (L7.4).


(b) Increase the time interval of computation. Compare the long time behavior of both problems
(L7.1) and (L7.4), in particular the amplitude of oscillations.
5. Solve numerically the IVP
d
2
y
dt
2
+ 4[y[
dy
dt
+ 3y = cos t, with y(0) = 1,
dy
dt
(0) = 0
in the interval 0 t 12. Is the behavior of the solution signicantly dierent from that of the
solution of (L7.4)? Comment. In particular, compare the size of the long term oscillations in y
with that of the problems (L7.1) and (L7.4).
6. Solve numerically the IVP
d
2
y
dt
2
+ 4y
dy
dt
+ 3y = cos t, with y(0) = 1,
dy
dt
(0) = 0
in the interval 0 t 12. Is the behavior of the solution signicantly dierent from that of the
solution of (L7.4)? Comment.
A Third-Order Problem
Consider the third-order IVP
d
3
y
dt
3
+ 4y
2
d
2
y
dt
2
+ 8y
_
dy
dt
_
2
+ 3
dy
dt
= sint, with y(0) = 1,
dy
dt
(0) = 0,
d
2
y
dt
2
(0) = 4. (L7.5)
Introducing v =
dy
dt
and w =
dy
2
dt
2
we obtain
dv
dt
= w and
dw
dt
=
d
3
y
dt
3
= sint4y
2
w8yv
2
3v. Moreover,
v(0) =
dy
dt
(0) = 0 and w(0) =
d
2
y
dt
2
(0) = 4. Thus (L7.5) is equivalent to
_

_
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

Figure L7d: Time series y = y(t), v = v(t) = y

(t), and w = w(t) = y

(t) (left), and 3D phase plot v = y

vs. y vs w = y

for (L7.5) (rotated with view = [-45,60]).


7. (a) Compare the output of Figs L7c and L7d. What do you notice?
(b) Dierentiate the ODE in (L7.4) and compare to the ODE in (L7.5).
(c) Explain why the solution of (L7.4) also satises the initial conditions in (L7.5).
(d) Solve the problems (L7.4) and (L7.5) using Eulers method with step-size h = .1. Are the
solutions identical? Comment.
Alternate Reduction
The choice of intermediate function v in the reduction of (L7.1) to rst-order ODEs is not limited to
v =
dy
dt
, although it is the simplest from a practical point of view. Other choices may be used, which
may be more revealing from a purely mathematical point of view or lead to more accurate numerical
results.
To reduce (L7.1) to a set of two rst-order ODEs consider for example the choice v =
dy
dt
+ y, i.e.,
dy
dt
= v y. Then
dv
dt
=
d
2
y
dt
2
+
dy
dt
=
_
cos t 4
dy
dt
3y
_
+
dy
dt
= cos t 3(v y) 3y = cos t 3v. (L7.7)
MATLAB sessions: Laboratory 7 77
To get an initial condition for v substitute t = 0 in the denition of v:
v(0) =
dy
dt
(0) +y(0) = 0 + (1) = 1. (L7.8)
Thus
(L7.1)
_
dy
dt
= v y,
dv
dt
= cos t 3v
with
_
y(0) = 1,
v(0) = 1.
(L7.9)
Note that (L7.7) is independent of y and can be integrated directly, either analytically here, or numeri-
cally, for v. The solution y can then be obtained from v by direct integration or numerical quadrature.
8. Solve (L7.9) numerically using ode45:
(a) by solving the problem as a system;
(b) by rst solving numerically for v (use only (L7.8) and (L7.9)), then use the following MATLAB
commands to obtain y:
% assume v was obtained as [tv,v] = ode45(...)
[ty,y] = ode45(@odey,[0,12],??,[],tv,v); % fill-in IC
...
%---------------------------------------
function dydt = odey(t,y,tv,ty)
v = interp1(tv,ty,t); % interpolate v
dydt = v-y;
(c) Compare the solutions with the one obtained using v = 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

MATLAB sessions: Laboratory 8 79


Equation (L8.2) is rewritten
d
2
y
dt
2
+
2
y = 0 (L8.3)
where
2
= k/m. Equation (L8.3) models simple harmonic motion. A numerical solution with ini-
tial conditions y(0) = 0.1 meter and y

(0) = 0 (i.e., the mass is initially stretched downward 10cms


and released, see setting (c) in gure) is obtained by rst reducing the ODE to rst-order ODEs (see
Laboratory 7).
Let v = y

. Then v

= y

=
2
y = 4y. Also v(0) = y

(0) = 0. The following MATLAB program


implements the problem (with = 2).
function lab8ex1
m = 1; % mass [kg]
k = 4; % spring constant [N/m]
omega = sqrt(k/m);
y0 = 0.1; v0 = 0; % initial conditions
[t,Y] = ode45(@f,[0,10],[y0,v0],[],omega); % solve for 0<t<10
y = Y(:,1); v = Y(:,2); % retrieve y, v from Y
figure(1); plot(t,y,b+-,t,v,ro-); % time series for y and v
%-----------------------------------------
function dYdt = f(t,Y,omega)
y = Y(1); v = Y(2);
dYdt = [ v ; -omega^2*y ];
Note that the parameter was passed as an argument to ode45 rather than set to its value = 2
directly in the function f. The advantage is that its value can easily be changed in the driver part of the
program rather than in the function, for example when multiple plots with dierent values of need to
be compared in a single MATLAB gure window.
0 1 2 3 4 5 6 7 8 9 10
0.2
0.15
0.1
0.05
0
0.05
0.1
0.15
0.2
Figure L8a: Harmonic motion
80 MATLAB sessions: Laboratory 8
1. From the graph in Fig. L8a answer the following questions.
(a) Which curve represents y = y(t)?
(b) What is the period of the motion?
(c) When will the mass-spring system come to rest? Why?
(d) What is the amplitude of the oscillations for y?
(e) What is the maximum velocity attained by the mass, and when is it attained?
(f) How does the size of the mass m and the stiness k of the spring aect the motion?
2. (a) Plot the quantity E =
1
2
mv
2
+
1
2
ky
2
as a function of time. What do you observe?
(b) Show analytically that
dE
dt
= 0.
(c) Plot v vs y (phase plot). Does the curve ever get close to the origin?
Mass-Spring System with Damping
When the movement of the mass is damped due to viscous eects (e.g., the mass moves in a cylinder
containing oil, situation (d)), an additional term proportional to the velocity must be added. The
resulting equation becomes
m
d
2
y
dt
2
+
dy
dt
+ky = 0 or
d
2
y
dt
2
+c
dy
dt
+
2
y = 0 (L8.4)
by setting c = /m. The program lab8ex1 is updated by modifying the function f:
function lab8ex1a
m = 1; % mass [kg]
k = 4; % spring constant [N/m]
gamma = 1; % friction coefficient [Ns/m]
omega = sqrt(k/m); c = gamma/m;
y0 = 0.1; v0 = 0; % initial conditions
[t,Y] = ode45(@f,[0,10],[y0,v0],[],omega,c); % solve for 0<t<10
y = Y(:,1); v = Y(:,2); % retrieve y, v from Y
figure(1); plot(t,y,b+-,t,v,ro-); % time series for y and v
%-------------------------------------------
function dYdt = f(t,Y,omega,c)
y = Y(1); v = Y(2);
dYdt = [ v ; ?? ]; % fill-in dv/dt
3. From the graph in Fig. L8b answer the following questions.
(a) For what minimal time t
1
will the mass-spring system satisfy [y(t)[ > 0.01 for all t > t
1
? You
can answer the question either by magnifying the MATLAB gure using the magnify button
, or use the following MATLAB commands (explain):
for i=1:length(y)
m(i)=max(abs(y(i:end)));
end
i = find(m<0.01); i = i(1);
disp([|y|<0.01 for t>t1 with num2str(t(i-1)) <t1< num2str(t(i))])
(b) What is the maximum velocity attained by the mass, and when is it attained?
(c) How does the size of aect the motion?
(d) Determine the smallest (critical) value of c (or ) such that no oscillation appears in the
solution. Demonstrate your result numerically.
MATLAB sessions: Laboratory 8 81
0 1 2 3 4 5 6 7 8 9 10
0.2
0.15
0.1
0.05
0
0.05
0.1
0.15
0.2
y(t)
v(t)=y(t)
Figure L8b: Damped harmonic motion
4. (a) Plot the quantity E =
1
2
mv
2
+
1
2
ky
2
as a function of time. What do you observe?
(b) Show analytically that
dE
dt
< 0 for > 0 while
dE
dt
> 0 for < 0.
(c) Plot v vs y (phase plot). Comment on the behavior of the curve.
The GUI masspring.m
The GUI masspring.m is a simple to use Graphical User Interface (written in MATLAB but this is trans-
parent to the user) useful for understanding how the solution of the mass-spring problem changes when
physical parameters such as the mass m, the friction coecient , the spring constant k, the initial condi-
tions y(0) and y

(0), are varied. The GUI is currently available at http://math.asu.edu/bdw/PUBLIC.


After download the GUI is launched in the MATLAB Command Window by entering
>> masspring
A new window which looks like Fig. L8c opens. The parameters can be changed in the edit boxes at
the top of the window. The solve button then solves the problem. The solution is displayed in
the lower left part of the window. If the parameters are changed and the problem solved again the axes
in the display are likely to change. To keep the previous axes, press the hold on button . To
release the axes, press the button again (now labelled hold off).
The GUI has two nice features.
Parameters can be continuously changed within a predened range. To select which parameter
82 MATLAB sessions: Laboratory 8
Figure L8c: The GUI masspring.m
to change select the appropriate item in the menu . Then use the slider
by continuously clicking on one of the directional arrows (left or right) or
simply moving the slider left or right while pressing the left mouse button. The solution is then
continuously updated in the graph area. It is recommended to set the hold button for this feature,
in order to better understand how changes in the parameter aect the solution.
The actual physical movement of the mass can be observed for a given setting of the parameters by
pressing the play button . At the same time a red marker moves on the trajectory displayed in
the graph area on the left to indicate the point on the solution curve corresponding to the current
elongation of the spring on the right. The current time is also displayed. The movement can be
paused using the button .
Finally the button resets parameter values to default values, while the button exits
the GUI.
5. Experiment with the GUI. In particular, review problems 1 through 4.
Note that the GUI masspring.m also handles forced vibrations, see Laboratory 10.
MATLAB sessions: Laboratory 9 83
Laboratory 9
The Pendulum
(4.7 of the Nagle/Sa/Snider text)
In this laboratory we model the motion of a (simple) pendulum with a second-order dierential equation.
A mass m is attached to a rigid rod rotating around a xed point. The rod makes an angle with the
downward positive vertical y-axis. Positive angles are oriented counter-clockwise, in the direction of the
positive x-axis.
c
y
E
x
qc
...............................................
.........................................................................................................................................................................................................................................................................................................................................................................................................................
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
d
d
d
d
d
d
d
dy

T
F
A
W
m
d
d
d
ds

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.5 rad/s. A MATLAB implementation follows.


84 MATLAB sessions: Laboratory 9
function lab9ex1
g = 9.81; % gravitational accel. [m/s^2]
l = 0.5; % pendulum length [m]
omega = sqrt(g/l);
theta0 = ??; v0 = ??; % fill-in ICs
[t,Y] = ode45(@f,[0,20],[theta0,v0],[],omega); % solve for 0<t<10
theta = Y(:,1); % retrieve theta
figure(1); plot(t,theta*180/pi,b-); % theta in degrees
grid on
%-----------------------------------------------
function dYdt = f(t,Y,omega)
theta = Y(1); v = Y(2);
dYdt = [ ?? ; ?? ]; % fill-in ODE
0 2 4 6 8 10 12 14 16 18 20
50
40
30
20
10
0
10
20
30
40
50
Figure L9a: Motion of a simple pendulum: = (t) (degrees).
1. From the graph in Fig. L9a answer the following questions.
(a) What is the period of the motion?
(b) Will the pendulum come to rest? Why?
(c) What is the maximal angle the pendulum makes with the vertical?
(d) Does the value of the mass m aect the plot?
2. Change the initial condition on the rate of change of to v(0) = 8.17 rd/s, v(0) = 8.175 rd/s, and
v(0) = 8.18 rd/s. Decide whether the behavior makes sense. How is the motion of the pendulum
modied compared to the previous situation? The following graph shows the case v(0) = 8.17 rd/s.
MATLAB sessions: Laboratory 9 85
0 2 4 6 8 10 12 14 16 18 20
200
150
100
50
0
50
100
150
200
3. Use the following options in ode45:
options = odeset(Reltol,1e-12,AbsTol,1e-12);
[t,Y] = ode45(@f,[0,20],[theta0,v0],options,omega);
Redo question 2. What has changed in the numerical procedure?
4. Try some of the following variations on the initial conditions:
(a) (0) = rad,

(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,

(0) = 0.03 rad/s.


(h) (0) = 7 rad,

(0) = 0.01 rad/s.


Comment on the behavior of the pendulum in each case. Are any of the behaviors realistic? Are
any of the behaviors not realistic? If so what is the explanation for the unrealistic behavior?
5. (a) Plot the quantity E =
1
2
m
_
d
dt
_
2
+mg(1cos ) as a function of time. What do you observe?
(b) Show analytically that
dE
dt
= 0.
(c) Plot v vs (phase plot). How does the curve behave?
86 MATLAB sessions: Laboratory 9
The Linearized Case
Lets know examine what happens when we substitute for sin in (L9.2). The new equation for is
thus
d
2

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) = 8.17 rad/s.


(e) (0) = 45 degrees,

(0) = 8.18 rad/s.


(f) (0) = 180 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,

(0) = 1 rad/s? Make sure


that you integrate the dierential equation over a suciently large time interval.
MATLAB sessions: Laboratory 10 89
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 nonhomogeneous equations. We will concentrate
on equations with a periodic harmonic forcing term. This will lead to a study of the phenomenon known
as resonance. The equation we consider has the form
d
2
y
dt
2
+c
dy
dt
+
2
y = sint. (L10.1)
This equation models the movement of a mass-spring system similar to the one described in Laboratory
8 page 78. The forcing term on the right-hand side of (L10.1) models a vibration, with amplitude 1 and
frequency (in radians per second =
1
2
rotation per second =
60
2
rotations per minute, or RPM) of
the plate holding the mass-spring system. All physical constants are assumed to be positive.
When
c
2
< the general solution of (L10.1) is
y(t) = ae

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

+2y = 0 into a set of two rst order linear ODEs and


use MATLAB to compute the eigenvalues, eigenvectors, and plot the phase plane of the resulting
ODE system (matrix). What happens to the solution when t ?
15. Consider the ODE system (L11.2) with A =
_
2 1
1 2
_
. Compute eigenvalues, eigenvectors and
plot the phase plane. What can you say about the direction of eigenvectors?
16. (matrix exponential) The solution of the problem (L11.2) can be written in the form
x(t) = e
tA
x(0),
where e
tA
is the matrix exponential of the matrix tA. Use the MATLAB function expm to obtain
the solution with initial condition x(0) =
_
1
0
_
. Compare with the solution computed by applying
directly ode45 to (L11.1).
102 MATLAB sessions: Laboratory 12
Laboratory 12
Additional Numerical Techniques
(3.6, 3.7 and 5.3 of the Nagle/Sa/Snider text)
In this laboratory we discuss several improvements on Eulers and improved Eulers methods for solving
scalar and systems of dierential equations, and introduce the notion of order of a numerical method.
This is done in the context of a simple rst-order equation as well as the aircraft guidance problem
introduced in Laboratory 6 page 67.
The objectives of this laboratory are as follows.
Get acquainted with xed-step numerical methods which is more accurate than Eulers method,
and apply them to an ODE system.
Understand what the order of a method represents and how to use it to a priori determine the
value of a step-size needed to reach a given accuracy.
Apply the ideas to problems where accuracy is important such as those arising in celestial mechan-
ics.
Taylor and Runge-Kutta Methods
The rst step of Eulers method for solving the IVP y

= f(t, y) with y(t


0
) = y
0
can be interpreted by
considering the truncation of the Taylor series expansion to rst-order terms, namely
y(t
1
) = y(t
0
+h)
y(t
0
) +hy

(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

(0) = 0 (left integrator).


The output Scope input port is y. To visualize this output rst run the simulation using the
Simulation > Start menu, then double-click on the Scope. The axis limits can be adjusted using the
button in the output window (titled Scope), see Figure L13c. The numerical integration parameters
for the model solution can also be adjusted (in particular the maximal integration step size and the
accuracy of the integration) using the Simulation > Simulation parameters... menu.
MATLAB sessions: Laboratory 13 109
Figure L13c: The spring1 model output in the Scope window.
1. Experiment with moving the dierent blocks in the model by dragging them with the mouse.
2. Experiment with changing the values of the parameters in the dierent blocks of the spring1
model.
3. Why is the integrator block labelled with the symbol
1
s
? Hint: think of the connection between
the Laplace transforms of 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

+ 4y = sint with y(0) = 1,


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

+4y = sin t, y(0) = 1, y

(0) = 0 using InvLaplace with homogeneous


and forced contributions.
If F(s) is unknown it must be computed numerically using NumLaplace. The inverse Laplace
transform of
F(s)
Q(s)
must then also be determined numerically using invlap. Because invlap requires for
each value of t the evaluation of
F(s)
Q(s)
at many (complex) s values this is a very expensive task:
Lab14b.m
function Lab14b
124 MATLAB sessions: Laboratory 14
% Solution of the IVP
% y+4y = sin(t) with y(0)=1, y(0)=0
% using numerical Laplace transforms
global Q
c = [1,0,4]; IC = [1,0];
t = .1:.1:20;
[P,Q] = free_response(c,IC);
disp(Laplace transform of y_free =); nice(P,Q,s)
y_h = InvLaplace(P,Q,0,t);
y_f = invlap(@F,t,0);
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)
%------------------------------------------------------------------------------------
function Fv = F(s)
global Q
Fv = zeros(size(s));
for i = 1:length(s)
Fv(i) = NumLaplace(@forcing,s(i));
end
Fv = Fv./polyval(Q{1},s);
%------------------------------------------------------------------------------------
function fv = forcing(t)
fv = sin(t);
Figure L14f shows that the numerical approximation obtained in Lab14b becomes inaccurate as t in-
creases. The ineciency and inaccuracy for larger values of t explain why Laplace transform methods are
not used numerically in practice and essentially require the use of a table or a set of rules to symbolically
determine the solution of an IVP as implemented in the MATLAB Symbolic Toolbox or MAPLE.
8. Use InvLaplace and/or NumLaplace/invlap to obtain a graph of the solution to the following
IVPs.
(a) y

+ 5y

+ 4y = 0 with y(0) = 1, y

(0) = 0, y

(0) = 4, y

(0) = 1.
(b) y

+ay

+y = sint with y(0) = 1, y

(0) = 0 for a = 5, 2, 1, 0.1.


(c) y

+ 4y =
_
sint for t <

2
1 for t 1
with y(0) = 1, y

(0) = 0.
(d) y

+y =mod(floor(t),2) with y(0) = 1, 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

(0) = 0 using NumLaplace and


InvLaplace/invlap with homogeneous and forced contributions.
126 MATLAB sessions: Laboratory 14
Chapter 4
Additional Project Descriptions
Note to the Instructor: Group Projects
One of the strengths of the Nagle, Sa and Snider text is the number of projects that are included at
the end of each chapter. The selection of projects is expanded in the new edition (6
th
ed., 2004) as it
includes a number of projects contributed by instructors who have used previous editions of the book.
MATLAB and SIMULINK can be used to assist with these projects in many ways.
The additional projects presented in this supplement illustrate that a project can be designed around
almost any topic. These projects represent a diverse set of applications, including chemical engineering,
mathematical epidemiology, special functions, electrical circuits, athletics, and an area where such ODE
techniques have been rarely applied - the dynamics of love. Likewise, the analytical tools required to
complete the investigation of the projects are varied. One of the models emphasizes the modelling
process more than the solution of the IVPs, and many of them involve systems of ODEs.
A brief overview of each project contained in this section is provided below. The actual description
comprises the remainder of this chapter (there is no specic ordering to the projects).
Design Your Own Project
The basic idea is for each (team of) student(s) to nd an application of dierential equations
related to a topic of personal interest - their major, another course in which they are currently
enrolled, or something that fascinates them - and prepare a project description, complete with a
derivation of a model, questions to be addressed, and realistic data. After the project description
is approved students have to prepare a project report.
The ODE of World-Class Sprint
This project is ideal for use with Chapter 2 of Nagle, Sa & Snider. The dierential equation
is linear (and separable). The real interest in this project is the mathematical modelling. The
application is easy to understand and discuss. The questions are not technically sophisticated,
but some of the underlying assumptions and interpretations are not completely trivial. Familiarity
with least-squares techniques is helpful, but not necessary, in Step III of the project.
Consecutive Reactions for Batch Reactors
This is another project that can be given very early in the semester. Even though the mathematical
model is a system of linear ODEs, the system is lower triangular and can be solved by forward
substitution.
The specic constants used in this lab do not pertain to any real situations. Its not unreasonable
to ask the students to research this problem and identify specic instances in which this model
arises as well as realistic parameter values.
This project originated from Ralph White, Chemical Engineering and Center for Electrochemical
Engineering, University of South Carolina, as part of a project funded by the Lilly Foundation and
the USC Oce of the Provost.
127
128 Additional Project Descriptions
Normal T-Cells
This project is Part I of a two-part problem. The second part (T-cells in the presence of HIV) is
appropriate only after systems of ODEs have been discussed. This project requires only the basics
of population modelling (constant, exponential, and logistic rates of change).
This project is an adaptation of the discussion presented by Herod and Yeagers (MapleTech, 1994),
which is based on a model proposed by Perelson et al. (Math. Biosc., 1993).
T-Cells in the Presence of HIV
This project is Part II of a two-part problem. The rst part (Normal T-cells) can be assigned
much earlier than this project (which involves a system of ODEs).
A third project in this series can be constructed around the question of possible treatments for
HIV/AIDS. An accessible discussion of this topic can be found in the paper Using Mathematics
to understand HIV immune dynamics by Denise Kirschner (Notices of the AMS 43(2) (February
1996) 191-202).
Design of an Electrical Network
This lab is based on a standard problem in electrical circuits. The focus is on the parametric
analysis of the solution as a function of one of the resistances in the network. Both the steady-
state solution and the manner in which the solution converges to the steady-state depend on the
value of this resistance.
This project requires knowledge about systems of linear ODEs. While it is ideally suited for
solution using matrix methods (Ch. 9), the project can be modied (see next comment) so that it
is not unreasonable to solve without the use of linear algebra.
The application requires Kirchhos voltage law, introduced in 3.5 (page 119) of Nagle, Sa and
Snider. Also, there are two values of the resistance for which the system does not have a full set
of eigenvectors. The treatment of this case is handled in problems 35-40 (9.5, page 543) and in
9.8, page 558.
The Dynamics of Love
This project is based on a dierential equations model developed by S. Rinaldi describing the
dynamics of love between two persons by accounting for their personalities (Laura and Petrarch:
an intriguing case of cyclical love dynamics, SIAM Journal on Applied Mathematics 58(4) (1998)
1205-1221). This type of project tends to excite the curiosity of the students who normally expect
to apply the knowledge they gained in the course to purely Engineering elds.
Hypergeometric Functions
A nice introduction to hypergeometric functions is presented in 8.8, page 484, of Nagle, Sa and
Snider. This project expands on the multitude of identities involving these functions.
Additional Project Descriptions 129
P1. Design your Own Project
Step I: Identify the Application
A variety of applications of dierential equations are discussed in the text and in this laboratory manual,
including Newtonian mechanics, population dynamics, electrical circuits, and mixing problems. The di-
versity of these applications illustrates the broad applicability of dierential equations. To add emphasis
to this point, this project requires that you identify an application of dierential equations in a subject
area of particular interest to you.
You are specically encouraged to discuss this project with a project mentor. This mentor should
be a professional scientist, e.g., a professor for another course you are presently taking or plan to take.
Provide a copy of this project assignment.
The application should be solvable by techniques discussed in this course. The only other requirement
is that the model have at least one parameter. The problem might involve a single higher-order or a
system of ordinary dierential equations, with appropriate initial values.
Step II: Background Investigation
The main result of this assignment will be a brief description of your project in the form of a project
assignment. Prior to writing this assignment, it will be necessary for you to thoroughly understand the
problem and the main questions that are to be addressed.
In consultation with your project mentor, you should identify a short list of references for your
application. These references should be accessible to students in your class, but they do not need to be
mathematical.
Study these references and pay special attention to the mathematical modelling used to convert the
physical problem into a mathematical problem, any assumptions that are made during the modelling
process, and the questions that will be the focus of the project description you will create (be sure to
request assistance and clarications from your mentor or dierential equations instructor, as needed).
Step III: Project Description
Prepare a project description for your project. This description should be no longer than two pages,
must be typed (including equations if any) and may include illustrations or other graphics as needed.
The project description should contain all of the following: title, your name/team members, the name
of your project mentor, a brief description of the physical problem, a summary of the mathematical
modelling, questions to be answered in the analysis, realistic values for all parameters, and references
related to the project.
Step IV: Summary and Conclusions
This project is longer than it sounds, unless you start early and divide the assignment into manageable
portions. It is important that you select relevant, interesting, and tractable questions. This may require
a few iterations before you nd the appropriate level. You may need to discuss your ideas with your
instructor and ask for help when needed.
In the end be sure that all questions are answered and that the nal report is similar in style to the
other project reports prepared for this course.
130 Additional Project Descriptions
P2. The ODE of World-Class Sprint
Understanding the Model
According to Kellers theory of competitive running, published in 1973, track sprints of up to 300 meters
can be described by the dierential equation
dv
dt
= A
v

.
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

for which f(T

) = 0. What is the signicance of 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

. Plot the results


using a surface plot (surf). Compare with the analytic expression obtained earlier.
7. Draw conclusions regarding the level of T

in terms of the parameters. Is this what you expected?


8. (optional) Create a SIMULINK model for this problem.
Bibliography
[1] Greene, W. C., AIDS and the Immune System, Scientic American (Sept. 1993, Special Issue).
[2] Herod, J. V., A Model for an HIV Infection, Maple Technical Newsletter 10 (1993) 72-78.
[3] Perelson, A.S., Kerschner, D. E. and Deboer, R., Dynamics of HIV Infections of CD4+ T-cells,
Mathematical Biosciences 114 (1993) 81-125.
Additional Project Descriptions 135
P5. T-Cells in the Presence of HIV
Background
In [3] Perelson, Kerschner, and DeBoer present a model for the interaction of T-cells and HIV. In the
project Normal T-cells we learned how T-cells function in a healthy individual. In this project we
discuss some of the changes needed to adapt the model in the presence of HIV in the body. This
discussion is more dicult than in the previous project. Thinking about the biological interpretation of
each term should help you understand the model. The nal qualitative results should be consistent with
what you know about T-cells, HIV and AIDS.
The general idea 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]. You may also want to
read rst, without necessarily investigating, the project Normal T-cells.
The Model
When attacked by the HIV virus T-cells are able to ght o the invasion for a period of time, but
eventually must give up to the onslaught. As a result, the immune system becomes less eective at
ghting diseases (including the spread of HIV). The models presented in this section incorporate some
of the forces involved in this process.
Once a T-cell is infected with the HIV virus, it can either become latent (i.e., not reproduce the
virus) or active (i.e., spread the virus). Therefore the new model must describe the evolution of four
dierent populations: the size V of the HIV population, the number T of healthy T-cells, the number
T
L
of latently infected T-cells, and the number T
A
of actively infected T-cells. A dierent dierential
equation is needed for each of T, T
L
, T
A
, and V . The complete model of four dierential equations is
assembled by considering each population separately.
Normal T-cells are produced and die according to processes identied in the earlier project. In
addition, interactions between healthy T-cells and the virus transfer some normal T-cells into
latently infected T-cells. The rate of change of healthy T-cells is then given by
dT
dt
= s +rT
_
1
T +T
L
+T
A
T
max
_
T k
1
V T = f
T
(T, T
L
, T
A
, V ).
The infected T-cells population increases as normal T-cells interact with the virus and decreases
due to both natural death and transfer to actively infected T-cells. The dierential equation
describing the rate of change of T
L
thus reads
dT
L
dt
= k
1
V T T
L
k
2
T
L
= f
T
L
(T, T
L
, T
A
, V ).
The actively infected T-cells population grows due to conversion of latently infected T-cells and
decreases due to viral replication. A model for the rate of change of actively infected T-cells is
then
dT
A
dt
= k
2
T
L
bT
A
= f
T
A
(T, T
L
, T
A
, V ).
Finally the viral population is assumed to grow at a rate proportional to the death rate of actively
infected T-cells (with constant of proportionality N). The only ways in which free virus is removed
is by combination with healthy T-cells or by clearance from the body (e.g. through transfusion).
The equation for the rate of change in the virus population is thus given by
dV
dt
= NbT
A
k
1
V T aV = f
V
(T, T
L
, T
A
, V ).
136 Additional Project Descriptions
Understanding the Parameters and Checking the Model
1. Assuming that each population is measured in cells per cubic millimeter and time is measured in
days, determine the units associated with each of the parameters.
2. The model remains appropriate as long as each population does not become negative. Starting
with T(0) > 0 the only way T can become negative is if
dT
dt
< 0 at some time t for which T(t) = 0.
But for T = 0 the rst ODE yields
dT
dt
= s > 0, guaranteing that T > 0 for all t. Determine
conditions on the parameters guaranteing that none of T
L
, T
A
, or V can ever become negative.
Steady-State Analysis
In this section we focus on two issues: what is the infected steady-state? How does an initial infection
evolve towards this steady-state?
3. Realistic values for the parameters are s = 10, r = 0.03, T
max
= 1700, = 0.02, b = 0.24, a = 2.4,
k
1
= 2.4 10
5
, k
2
= 3 10
3
, and N = 1400. What are reasonable initial conditions for T, T
L
,
and T
A
? Determine numerically the solution of the system of four ODEs with initial conditions
V (0) = 10
3
over the interval 0 t 150. Create one plot showing T
L
, T
A
, and V . Create a
separate plot showing the evolution of the healthy T-cells. Why is this population not included in
the other plot?
4. Note the dramatic initial increase in the (free) virus population. Which term in the equation for
V is responsible for this behavior? What is the biological explanation for this?
5. Determine an analytic expression for the steady state value T

of T. Compare to the value of T


at t = 150.
6. Continue the calculation until T converges to its steady-state. What is the value of this steady-
state? How does this value compare to the steady-state obtained with initial condition V (0) = 0
instead? When does the healthy T-cell count rst drop below the normal range for a healthy
individual? How much longer does it take for the solution to converge to a steady-state solution?
Is is likely that this transition will occur during the patients lifetime?
7. Experiment with a range of values for N. Does the infected steady-state always exist?
8. (optional) Create a SIMULINK model for this model.
Concluding Remarks and Extensions
The model developed in this problem is consistent with the current understanding of the transition from
infection with HIV to the onset of AIDS. That is, immediately after infection there is an enhanced
level of infected T-cells. After only a few days these levels become so low they are undetectable using
typical testing procedures. During this period the normal T-cell population is strong enough to combat
the virus. However, the level of T-cell production cannot be maintained forever. At some point AIDS
becomes detectable as the T-cell concentration drops to a fraction of the necessary level.
While the overall picture presented by this model is rather bleak, there are some bright spots. In
particular, this model suggests that the onset of AIDS can be delayed if healthy T-cell production can
be extended. This is the idea behind some of the drugs already being tested and used for the treatment
of AIDS.
NOTE added: A simplied model combining both latent and actively infected populations into a
single infected state I is also included in [4]. An interesting exercise would be to compare the two
models and test the validity of the simpler model as a suitable reduction of the model used here. Model
reduction is an important aspect of the modelling process because it makes the problem mathematically
more tractable and generally provides additional insight into the fundamental properties of the original
problem.
Additional Project Descriptions 137
Bibliography
[1] Greene, W. C., AIDS and the Immune System, Scientic American (Sept. 1993, Special Issue).
[2] Herod, J. V., A Model for an HIV Infection, Maple Technical Newsletter 10 (1993) 72-78.
[3] Perelson, A.S., Kerschner, D. E. and Deboer, R., Dynamics of HIV Infections of CD4+ T-cells,
Mathematical Biosciences 114 (1993) 81-125.
[3] Culshaw, R. V. and Ruan, S, A delay-dierential equation model of HIV infection of CD4+ T-cells,
Mathematical Biosciences 165 (2000) 27-39.
138 Additional Project Descriptions
P6. Design of an Electrical Network
Understanding the Problem
The objective of this project is to design an electrical network to meet specic design criteria. The
network consists of two loops, see Figure 1. The left loop contains a E = 12 Volt emf and a L = 1 Henry
inductor. The right loop contains a C =
1
4
Farad capacitor and a R = 6 Ohm resistor. A resistor with
unspecied resistance r is on the common side of both loops. There is no current in the network until a
switch, located in the left loop, is closed.
e
e
e
e
e
e

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) =

F( + 1, + 1, + 1; x) holds for 1 < x < 1


(a) analytically by dierentiating the series (2) termwise.
(b) analytically by showing that
d
dx
F(, , ; x) satises an appropriate dierential equation with
suitable initial conditions.
(c) numerically by comparing the direct evaluation of F(, , ; x) via hypergeom.m with

_
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

You might also like