You are on page 1of 155

MATLABr Laboratory Manual

with SIMULINKr examples

Bruno D. Welfert

to accompany

Fundamentals of
Differential Equations
Sixth Edition

and

Fundamentals of
Differential Equations
and
Boundary Value Problems
Fourth Edition

Nagle Saff Snider


i
MATLABr and SIMULINKr are registered trademarks of The MathWorks, Inc.
MAPLEr 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 Differential Equations


with MATLAB 19
Numerical Differentiation 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 Differential Equations, Graphical Analysis . . . . . . . . . . . . . . . 38
Direction fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Additional Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Laboratory 2: Numerical Solutions (Euler, Improved Euler) for Scalar Equations . . . . . . . . 42
Euler’s Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Improved Euler’s 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 Differential Equations . . . . . . . . . . . . . . . . . 61
Population Growth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Other Models, Parameter Estimation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Laboratory 6: Further Applications of First-Order Differential Equations . . . . . . . . . . . . 66

iii
The Snowplow Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Aircraft Guidance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Heating and Cooling of Buildings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Laboratory 7: Implementing Higher-Order Differential 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 Differential Equations (and
Boundary Value Problems) by Nagle, Saff 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 specific 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 differential
equations and visualizing and interpreting their solutions. The main objectives are:
1. familiarize students with basic MATLAB programming to solve differential equations of varying
complexity,
2. provide a platform for testing and experimenting with fundamental aspects of numerical compu-
tations of solutions of differential 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 specific 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 first 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 file, which is important in creating programs that implement a whole problem. The
second chapter is more specific to differential 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 differential equations. This is done in
the context of specific 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 difficulty, 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 different 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 Differential
Equations with MATLAB course I have been teaching is also included. Each project is briefly 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 significant 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 effort 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 LATEX document preparation system. PostScript figures
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, Saff 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 briefly used
in this manual. A detailed description is available in their book Ordinary Differential 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 files.

The MATLAB Environment

F 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 find the Command Window, where commands are entered at
the prompt >>.
On the left side you will generally find 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 files 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.
F 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.
F Basic operations are +, -, *, and /. The sequence
>> a=2; b=3; a+b, a*b,

ans =

ans =

1
2 Introduction to MATLAB

Figure 1.1: A typical MATLAB desktop

defines 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 ,.
F Standard functions can be invoked using their usual mathematical notations. For example
>> theta=pi/5;
>> cos(theta)^2+sin(theta)^2

ans =

verifies the trigonometric identity sin2 θ + cos2 θ = 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.

F 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.

F 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".

F 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.
F 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

F 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


F 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
x2 − sin(πx) + ex
y = f (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

F Note that an ellipsis ... was used to continue a command too long to fit in a single line.
F 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 infinite 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 figure can be edited and manipulated
using the Figure window menus and buttons. Alternately, properties of the figure can also be defined
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

f(x)=(x2−sin(π x)+ex)/(x−1)
20

15

10

5
y

−5

−10
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
x

x2 −sin(πx)+ex
Figure 1.3: The function y = f (x) = x−1 .
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


F Files containing MATLAB commands are called m-files and have a .m extension. They are two types:

1. A script is simply a collection of MATLAB commands gathered in a single file. 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 specified
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 defining the output.

Use a function when a group of commands needs to be evaluated multiple times.


F To create a new script or function select the MATLAB desktop File menu File > New > M-file.
In the MATLAB text editor window enter the commands as you would in the Command window. To
save the file 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.

F 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 files)


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


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-file (just as other predefined MATLAB functions).
In case 3 myfunction.m can be used by any other function in the same m-file (myplot1.m) only. Use 3
when dealing with a single project and 2 when a function is used by several projects.
F It is convenient to add descriptive comments into the script file. Anything appearing after % on any
given line is understood as a comment (in green in the MATLAB text editor).
F 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
file 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 modification 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 files in the Current Directory (folder). When entering MATLAB the
Current Directory is the Work Directory (e.g., C:\matlabR12\work). Make sure the file 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.
F A function file 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 defined 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 file 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.
F Matrices
  can be constructed in MATLAB in different ways. For example the 3 × 3 matrix A =
8 1 6
3 5 7 can be entered as
4 9 2
>> 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 defined 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
F Some matrices are already predefined 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?)
F 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.
F Two MATLAB commands are especially relevant when studying the solution of linear systems of
differentials equations:
1. x=A\b 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
coefficients of D) (note that the eig function has one input and two output arguments).
 
1
As an example consider the matrix A =magic(3) again and x = 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 (fixed number of times)

for <expression>
<list of commands>
end

2. repetitive loops (indefinite 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

X 1 π2
What is the value of S returned by this script? Compare to = .
k2 6
k=1
Can k and incr be both initialized by 0?
1
3. if statement: evaluate y = x−2 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.
F Whenever possible all these construct should be avoided and available MATLAB functions used to
improve efficiency. 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

F 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 sufficient to find 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 specific 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 file 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 Differential Equations


with MATLAB

In this chapter we demonstrate the use of MATLAB in working with ordinary differential equations
(ODE) and initial value problems (IVP) of the form
½
y 0 = f (t, y),
y(t0 ) = y0 .

In particular, we discuss the following topics:

1. Numerical differentiation and solution of the IVP.

2. Direction fields and graphical solution (§1.3 and §5.4 of the Nagle/Saff/Snider text).

3. Numerical solution of first-order scalar IVPs using standard MATLAB routines (§3.6 and §5.3 of
the Nagle/Saff/Snider text).

4. Systems of ordinary differential equations (§5.2, §5.4, and §5.5 of the Nagle/Saff/Snider text).

Numerical Differentiation and Solution of the IVP


Consider the linear ODE y 0 = t2 − y. To (numerically) verify that y(t) = t2 − 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 y’s and t’s
>> 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 0 ) and rhs (= f (t, y) = t2 − y). Better accuracy
is obtained for smaller h.

19
20 Ordinary Differential Equations with MATLAB

−1

−2

−3

−4
−4 −3 −2 −1 0 1 2 3 4

Figure 2.1: Numerical comparison between of y 0 and t2 − y

Direction Fields
(§1.3, 5.4 of the Nagle/Saff/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 0 . When y 0 varies in a wide range a better perception of the
direction of the field 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 file which can be reused for different ODEs... This is left for
Laboratory 1 page 114.
F Approximate verification that a given function is solution of a particular ODE can also be done by
simply superposing the function to the direction field. 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 Differential Equations with MATLAB 21

−1

−2

−3

−4
−4 −3 −2 −1 0 1 2 3 4
4

−1

−2

−3

−4
−4 −3 −2 −1 0 1 2 3 4

Figure 2.2: Direction field for y 0 = t2 − y (left: constant dt, right: scaled dt).
22 Ordinary Differential Equations with MATLAB

−1

−2

−3

−4
−4 −3 −2 −1 0 1 2 3 4

Figure 2.3: Direction field for y 0 = t2 − y with particular solution.

F The Graphical User Interface dfield6 from J. Polking (available at http://math.rice.edu/∼dfield)


can also be used to plot the direction field 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 Differential Equations with MATLAB 23

Figure 2.4: The dfield6 setup GUI

Figure 2.5: The dfield6 direction field plot


24 Ordinary Differential Equations with MATLAB

First-Order Scalar IVP


(§3.6, 5.3 of the Nagle/Saff/Snider text)

Consider the IVP ½


y 0 = t − y,
(2.1)
y(0) = 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 first-order ODEs the function may often be specified using the inline
MATLAB command. A complete MATLAB solution would read:
Ordinary Differential 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 defines 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 first argument is the function f, the second one determines the time interval on
which to solve the IVP in the form [initial time, final time], and the last one specifies 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 Differential 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 specific 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 figure window. The plot, shown in Figure 2.6, can be saved or
exported in various formats using the File menu of the figure window.

2.2

1.8

1.6

1.4

1.2

0.8

0.6
0 0.5 1 1.5 2 2.5 3

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 difference between the exact solution y(t) = t − 1 + 2e−t and the numerical approximation obtained
from ode45. Since this approximation is only given at specified 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 Differential 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 Differential Equations with MATLAB

−5
10

−6
10

−7
10

−8
10
0 0.5 1 1.5 2 2.5 3

Figure 2.7: Error in the solution of (2.1) computed by ode45.

−10
10

−11
10

−12
10

−13
10

−14
10

−15
10

−16
10
0 0.5 1 1.5 2 2.5 3

Figure 2.8: Error in the solution of (2.1) computed by ode45 with a better accuracy.
Ordinary Differential Equations with MATLAB 29

Integration
For initial value problems of the form

y 0 = f (t), y(t0 ) = y0 , (2.2)

the solution can be explicitly obtained as


Z t
y(t) = y0 + f (u)du. (2.3)
t0

To obtain a numerical approximation of y at some t 6= t0 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 file, included in the same file as the calling sequence of
ode45 (as below) or saved in a separate m-file (see page 10). Consider for example the IVP
½ 0
y = −a (y − e−t ) − e−t ,
(2.4)
y(0) = 1.

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 file contains at least two functions (a driver + a function).
Line 2 sets the initial data and the final time. Line 3 sets a particular value for the parameter a. In line
4 the parameter is passed to ode45 as the 5th argument (the 4th 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 Differential Equations with MATLAB

are used). Correspondingly the function f defined lines 8-9 must include a 3rd 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-file 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
F The additional line 6 in the file 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 stiff. Stiffness has to do with how fast nearby solutions
approach the solution of (2.4), see Figure 2.9.
y ’ = − a (y − exp( − t)) − exp( − t) a=1 y ’ = − a (y − exp( − t)) − exp( − t) a = 1000

1 1

0.99 0.99

0.98 0.98

0.97 0.97

0.96 0.96

0.95 0.95
y

0.94 0.94

0.93 0.93

0.92 0.92

0.91 0.91

0.9 0.9

0 0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.1 0 0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.1
t t

Figure 2.9: Direction field 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).

F Other MATLAB ODE solvers are designed to better handle stiff 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 Differential Equations with MATLAB 31

Higher-Order and Systems of IVPs


(§5.2, 5.4, 5.5 of the Nagle/Saff/Snider text)

We show here how to extend the use of ode45 to systems of first-order ODEs (the same holds for other
solvers such as ode15s). Higher-order ODEs can first be transformed into a system of first-order ODEs
to fit into this framework. See Lab 7 page 72 to find out how to do this.
As an example consider the system (Lotka-Volterra) representing the evolution of two populations
u1 = u1 (t) and u2 = u2 (t): 
 du1 = au − bu u ,
 1 1 2
dt (2.5)
 du2 = −cu2 + du1 u2

dt
with initial populations u1 (0) = 10 and u2 (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 significance 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 defined 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 defines the initial condition for both u1 and u2 . In line 4 the parameters
are passed to the ODE solver ode45 as extra arguments (starting from the 5th ), 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 u1 and u2 , 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 defining
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 specific value of t the input y to f is a 2 × 1 vector,
whose coefficients are the values of u1 and u2 at time t. Rather than referring to y(1) and y(2) in the
definition 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 defines the right-hand sides of the ODE system as a 2 × 1 vector: the first
coefficient is the first right-hand side ( du du2
dt ) and the second coefficient the second right-hand side ( dt ).
1

F Lines 6-10 correspond to the visualization of the results in a single figure. The subplot command
is used somewhat creatively here. The plot includes the time series of u1 and u2 , and a phase plot
representing the evolution of u2 in terms of u1 . Because the scales of u1 and u2 are different it is best
using two different graphs for u1 and u2 here. Note that u1 and u2 vary cyclically. The periodic evolution
of the two populations becomes clear from the closed curve u2 vs. u1 in the phase plot.
32 Ordinary Differential Equations with MATLAB

15

10
u1

0
0 2 4 6 8 10 12 14 16 18 20
150

100
u2

50

0
0 2 4 6 8 10 12 14 16 18 20

140

120

100
u2

80

60

40
0 5 10 15
u1

Figure 2.10: Lotka-Volterra example.

F 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) u1 vs. t

subplot(4,1,2) u2 vs. t
-

subplot(2,1,2) u2 vs. u1

F A phase plot can be obtained without solving the ODE system (2.5). Divide corresponding sides of
(2.5) to get
du2 −cu2 + du1 u2
= = f (u1 , u2 ). (2.6)
du1 au1 − bu1 u2
Ordinary Differential Equations with MATLAB 33

The phase plot of (2.5) is simply the direction field of (2.6). Because the independent variable u1 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’);

140

130

120

110

100

90

80

70

60

50

40

0 5 10 15

Figure 2.11: Phase plane for the ODE (2.6) using dirfield.

F 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 briefly 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 Differential 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 differential equations. In this chapter, we present 13 laboratory sessions for use in
an introductory class on differential equations. The idea behind these labs is to coordinate the use of
MATLAB with class instruction in differential equations.
The MATLAB sessions deal with many of the most important numerical aspects of solving differential
equations as well as building and understanding ODE models. Many of the labs are connected with the
material presented in the text Fundamentals of Differential Equations by Nagle, Saff 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 differential equations are solved numerically. Using MATLAB presents several advantages. The
student will

• easily visualize the behavior of solutions by means of direction fields 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 differential equations;

• be able to examine “what-if” situations to discover properties of differential equations;

• solve different types of problems from various fields 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 differential 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
fill-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 Differential Equations, Graphical Analysis Using Direction


Fields
(§1.3 in Nagle/Saff/Snider text)
In this laboratory the students are shown how to plot direction fields for first-order differential

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
field.
• Laboratory 2: Numerical solutions by Euler and Improved Euler methods (scalar eqs.)
(§1.4 and §3.6 in Nagle/Saff/Snider text)
This lab briefly explains Euler’s and Improved Euler’s 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/Saff/Snider text)
Students are shown how small changes in the initial condition may yield very different 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
field, as well as understand how to obtain equilibrium solutions.
• Laboratory 4: Picard Iteration
(Ch. 1, Project B, page 32 in the Nagle/Saff/Snider text)
This laboratory deals with Picard’s method for solving an IVP. The method is first 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 Differential Equations
(Ch. 3 of the Nagle/Saff/Snider text)
This is the first of two labs on applications of first-order differential equations. The idea is to
model real world phenomena by means of differential equations. First, three standard models are
discussed for population growth - the exponential, logistic, and modified logistic (also known as
Nagumo) models. Direction fields are generated to study the behavior of solutions to differential
equations modelling the growth. Other phenomena such as cooling modelled by Newton’s law of
cooling, the spread of diseases, and a mixing problem, are discussed.
• Laboratory 6: Further Applications of First-Order Differential Equations
(Project B of Ch. 2/Ch. 3 of the Nagle/Saff/Snider text)
This is the second of two labs on applications of differential 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, Saff & Snider text. MATLAB can easily handle such problems with varying parameters.
Many pieces of code are supplied.
• Laboratory 7: Implementing Higher-Order Differential Equations
(Ch. 4, 6 of the Nagle/Saff/Snider text)
This laboratory begins the study of second- and higher-order differential equations. The student is
taught first how to reduce higher-order ODEs to sets of first-order differential 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. Euler’s 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/Saff/Snider text)
This laboratory focuses on the harmonic oscillation of a mass-spring system, first without, then
with damping. The model is explained in terms of mechanical forces. Students are shown the
effect 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/Saff/Snider text)
This is another application of second-order differential 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 effect 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/Saff/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 first 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/Saff/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/Saff/Snider text)
In this laboratory the notion of order of a numerical method is introduced and illustrated with
numerical techniques somewhat more sophisticated than Euler’s 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 differential 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 difficulty in evaluating the transform nume2ically.
38 MATLAB sessions: Laboratory 1

Laboratory 1
First-Order Differential Equations
Graphical Analysis Using Direction Fields
(§1.3 in the Nagle/Saff/Snider text)

In this laboratory session we look at scalar first-order differential equations from a graphical viewpoint
and make use of direction fields. Our goal is to learn how to

1. create a function for plotting the direction field of a given ODE.

2. interpret the direction field to obtain pertinent information about solutions to the ODE.

Direction fields
A direction field for a scalar first-order differential 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 field provides
a simple way to “visualize” solutions without actually solving the ODE.
Consider the ODE
dy
= y 0 = 1 − sin y. (L1.1)
dt
We use the script page 20 to create a function file 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 file 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 defined in Lab1a.m so as to accept matrix arguments. Make sure both
files 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.

Direction field of y’=1−sin y

10

−2

−4

−6

−8

−10
−10 −8 −6 −4 −2 0 2 4 6 8 10

Figure L1a: Direction field of y 0 = 1 − sin y

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 dfield6.m to check the shape of the direction field shown in Fig. L1a and draw
some of the solutions (by clicking within the direction field window obtained) to confirm your
observations. Fig. L1b shows what you should obtain.

Figure L1b: Direction field of y 0 = 1 − sin y and sample solutions using DFIELD6

2. Consider the differential equation


dy
= y 0 = y(y + 1)(y − 2). (L1.2)
dt
(a) Examine the direction field 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,
Saff, and Snider.)
1
(c) If y(0) = 2 can y eventually be −1? Why?
3. Use dirfield.m AND dfield6.m to plot the direction field and some solution curves for each of
the following differential 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 0 = sin t.
(b) y 0 = sin y.
(c) y 0 = sin t sin y.

Additional Problems
4. For each of the following ODEs plot the direction field 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?

1 y
i. y 0 = 2y + t ii. y 0 = sin t − 2

5. For what values of t or y is the ODE y 0 = − yt defined? Illustrate and discuss the behavior of
solutions.
6. Show that a solution y = y(t) of y 0 = f (t, y) is even if f is an odd function of t (i.e., f (−t, y) =
−f (t, y)). Use this to find a few ODEs whose solutions are symmetric with respect to the y-axis.
Verify by plotting the direction field.
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/Saff/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 Euler’s method as well as an improved version to numerically solve an IVP.
2. Compare the accuracy and efficiency of the methods with methods readily available in MATLAB.
3. Apply the methods to specific problems and investigate potential pitfalls of the methods.

Euler’s Method
To derive Euler’s method start from y(t0 ) = y0 and consider a Taylor expansion at t1 = t0 + h:

y(t1 ) = y(t0 ) + y 0 (t0 )(t1 − t0 ) + . . .


= y0 + hf (t0 , y(t0 )) + . . .
= y0 + hf (t0 , y0 ) + . . .

For small enough h we get an approximation y1 for y(t1 ) by suppressing the . . ., namely

y1 = y0 + hf (t0 , y0 ). (L2.1)

Note that the IVP y 0 = f (t, y), y(t0 ) = y0 can be reformulated as


Z t1
y(t1 ) = y(t0 ) + f (s, y(s))ds. (L2.2)
t0

Then (L2.1) amounts to approximating the integral in (L2.2) using a left point rule.
The iteration (L2.1) is repeated to obtain y2 ' y(t2 ), . . . such that

yn+1 = yn + hf (tn , yn )
tn+1 = tn + h
y(t1 )
Geometrically, the approximation made is equivalent to replacing the y1 s
¡
solution curve by the tangent line at (t0 , y0 ). From the figure we have ¡
....

s ¡....... θ
y1 − y0 y0 ¡
..
f (t0 , y0 ) = f (t0 , y(t0 )) = y 0 (t0 ) = tan θ = ,
h ¡
¡
from which (L2.1) follows.

h
As an example consider the IVP t0 t1
y 0 = 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 Euler’s method we start with the initial condition and select a step size h.
Since we are constructing arrays t and y without dimensionalizing them first 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 first 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 1 × 6 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;

7.5
8

7 7.5

6.5 7

6.5
6

6
5.5

5.5
5
5

4.5
4.5

4
4

3.5 3.5

3 3
0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5 0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5

0.5
Figure L2a: Euler’s method applied to y 0 = 2y, y(0) = 3 with step h = 0.1 (left) and h = 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 Euler’s 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 difference in vertical (y) scale. To compare the
two approximations we plot both approximations on the same figure, together with the exact solution
y(t) = 3e2t :

>> [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);

8 Euler N = 5
Euler N = 50
Exact
7.5

6.5

5.5

4.5

3.5

3
0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5

Figure L2b: Euler’s method applied to y 0 = 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 figure. 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 Euler’s method explain why both Euler
approximations underestimate the exact solution in this particular example.
(b) If the error is defined 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 confirm
your conclusions.
2. Consider the IVP y 0 = −2y, y(0) = 3.

(a) Draw the direction field. 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 = 2k steps for
k = 2, . . . , 7. Plot curves on different subplots of the same figure. 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 field and the graphical interpretation of Euler’s method.

Improved Euler’s Method


The improved Euler’s method is most easily described by considering the expression (L2.2). Using a
trapezoidal approximation for the integral leads to
h
y(t1 ) ' y(t0 ) + (f (t0 , y(t0 )) + f (t1 , y(t1 ))) ,
2
i.e.,
h
y(t1 ) = y(t0 ) +
(f (t0 , y(t0 )) + f (t1 , y(t1 ))) + . . . . (L2.3)
2
Then substitute y(t0 ) = y0 and define y1 ' y(t1 ) by removing the . . . in (L2.3):

h
y1 = y0 + (f (t0 , y0 ) + f (t1 , y1 )) . (L2.4)
2
In other words y1 is obtained from y0 by using an average of f values, i.e., a slope average. The equation
(L2.4) defines the trapezoidal method. Unfortunately, this formula defines y1 only implicitly, i.e., y1
appears on both sides of the equality so that an equation must be solved to obtain y1 . To avoid this
problem, and since we already have made an approximation to get (L2.4), we replace y1 on the right-
hand side by the approximation one would obtain by simply applying Euler’s method from (t0 , y0 ). The
resulting quantity µ ¶
h
y1 = y0 + f (t0 , y0 ) + f (t1 , y0 + hf (t0 , y0 ) ) (L2.5)
2 | {z }
Euler y1 from (L2.1)

with t1 = t0 + 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 y2 ' y(t2 ), . . .,
i.e.,
µ ¶
yn+1 = yn + h2 f (tn , yn ) + f (tn + h, yn + hf (tn , yn ))
tn+1 = tn + h

Minor modifications 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 Euler’s 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 0 = 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 0 = −2y, y(0) = 3. Determine the improved Euler approximations in the
interval 0 ≤ t ≤ 10 using N = 2k steps for k = 2, . . . , 7. Plot curves on different subplots of the
same figure. What do you observe for small values of N (i.e., large h)? Compare to the results
obtained for Euler’s method.

Additional Problems
5. Repeat problems 2 and 4 for the IVP y 0 = 2y − 12e−2t , y(0) = 2. How does this problem differ
from problem 2?

6. Repeat problems 2 and 4 for the IVP y 0 = y(3 − y), y(0) = 2.

7. A child situated at the point (0, Y0 ) on the positive y-axis is dragging a toy on a string. He begins
pulling the toy initially resting at (x0 , 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 differential equation describing the EE


E
trajectory followed by the toy is
E

dy 0 a2 − x2
=y =− with y(x0 ) = 0
dx x Y s
p A
and a = x20 + Y02 (hint: consider the angle θ and A
A
the length of the string, see figure). A
(b) Use both Euler’s and improved Euler’s methods with A
a = 10, x0 = 8 and N = 78 steps to obtain a numer- Y0 s A
@ A
ical approximation for 0.2 ≤ x ≤ 8 (i.e., h = −0.1). @ θ.........A...
..
(c) Compare the approximations obtained to the solu- y @..... As
.

tion obtained using ode45.m. Compare the result @


@
with the exact solution @
à √ ! @s
p x 0 a + a 2 − x2 x x0
y(x) = Y0 − a2 − x2 + a ln .
x a + Y0
(d) Is the trajectory independent of the velocity v? Show that x, y and t are related by
p
y + a2 − x2 = vt + Y0 . (L2.6)

(e) Differentiate (L2.6) and show that



x a2 − x2
dx = − vdt.
a2

xn a2 −x2n
(f) Repeat part (b) using a variable hn = − a2 vδt instead, with xa0 Y2 0 vδt = 0.1 (so that
h0 = h = −0.1).
Note: euler.m and impeuler.m need to be modified 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 hn < h for x ' x0 and x small, but hn > 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/Saff/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 amplified (or
reduced).

2. Identify situations where multiple solutions coexist.

First consider the IVP y 0 = y with y(0) = 1. Let’s apply Euler’s 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 different 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 modified
when the initial condition is perturbed.

Dependence of the Solution of IVPs on the Initial Condition


To determine the effect of a change δy0 in the initial condition y0 has on the solution y(t) of the IVP
½ 0
y = f (t, y),
(L3.1)
y(t0 ) = y0

at a fixed time, consider y as a function of t as well as y0 and differentiate (L3.1) with respect to y0 . We
obtain
∂f
δy 0 (t) = δf (t, y(t)) = (t, y(t)) δy(t) (chain rule).
∂y
On the other hand
d d
δy 0 (t) = δ y(t) = δy(t) = (δy)0 (derivatives commute).
dt dt
Thus δy satisfies the linear ODE
∂f
(δy)0 = (t, y(t)) δy (L3.2)
∂y
(assume y(t) is known). An initial condition for δy is obtained by differentiating the IC in (L3.1):

δy(t0 ) = δy0 . (L3.3)

The solution of the linear IVP (L3.2-L3.3) is given by


µZ t ¶
∂f
δy(t) = δy0 exp (s, y(s)) ds . (L3.4)
t0 ∂y

The relation (L3.4) shows that a perturbation in the initial condition ³R y0 creates a perturbation
´ in the
t ∂f
solution y(t) at a later time t > t0 with an amplification factor exp t0 ∂y (s, y(s)) ds . It encapsulates
all significant results of interest in this laboratory session. In particular
∂f
• if ∂y > 0 perturbations are amplified (a dangerous situation),
∂f
• if ∂y < 0 perturbations are damped (a good situation),
Rt
• the only way to have δy(t) = 0 in regions where t0 ∂f ∂f
∂y (s, y(s)) ds is bounded (e.g., where ∂y is
continuous) is to have δy0 = 0 (exp 6= 0), i.e., trajectories starting with different initial conditions
cannot cross,
Rt
• if t0 ∂f ∂f
∂y (s, y(s)) ds = +∞ for some t (in particular when ∂y is not continuous) then infinitesimally
small (0) perturbations in y0 can create finite perturbations in y(t) (“0 × ∞” may be finite). This
means that two different 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/Saff/Snider text).

Two specific situations are of interest:


MATLAB sessions: Laboratory 3 51

1. (pure integration) For ODEs of the form y 0 = f (t) (i.e., f does not explicitly depend on y) we have
∂f 0 t
∂y = 0 so that the relation (L3.4) becomes δy(t) = δy0 . as an example consider the ODE y = e .
The direction field and several solution curves are shown in Fig. L3a, left. The field 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 0 = f (y) (i.e., f does not explicitly depend on t, such
an ODE is called autonomous) regions where f 0 (y) > 0 are regions where perturbations expand
and regions where f 0 (y) < 0 are regions where perturbations contract. As an example consider the
ODEs y 0 = y (f 0 (y) = 1, expanding solutions) and y 0 = −y (f 0 (y) = −1, contracting solutions).
The direction field and several solution curves are shown in Fig. L3a, center and right. The field
direction is the same for all points situated on the same horizontal line y = cst.

4 4 4

3 3 3

2 2 2

1 1 1

0 0 0

−1 −1 −1

−2 −2 −2

−3 −3 −3

−4 −4 −4
−2 −1 0 1 2 −2 −1 0 1 2 −2 −1 0 1 2

Figure L3a: Direction field of y 0 = et (left), y 0 = y (center), and y 0 = −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.
t
1. Consider the ODE y 0 = t2 −1 y for t ≥ 0, t 6= 1.

(a) Using (L3.4) show that perturbations in the initial value contract for t < 1 and expand for
t > 1. Confirm by plotting the direction field.
(b) Use ode45 to obtain the solutions on the interval 0 ≤ t ≤ 2 with initial condition y(0) = a
for a = 0, 12 , 1, 2. To do this complete and run the following m-file:
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 field. 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.
½ 0
y = y(1 − y),
2. Consider the (nonlinear) IVP
y(0) = y0 .

(a) Draw the direction field and solution curves corresponding to y0 = −1, 0, 21 , 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 y0 = 12 . Experiment with step
sizes. Is the long term approximation sensitive to the step size used?
F 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 field. For example the IVPs
½ 0 ½ 0
y = et , y = y,
and
y(0) = 1 y(0) = 1

have a common solution y(t) = et . However the two problems differ 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 amplification 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 √
= 2 y. (L3.5)
dt
We recall the following existence and uniqueness result:

If f (t, y) and ∂f∂t (t, y) are continuous everywhere within a region containing (t0 , y0 ) then the IVP y =
0

f (t, y), y(t0 ) = y0 , has a solution valid on some (possibly small) time interval around t0 , and this solution
is unique.


In the case (L3.5) we have f (t, y) = 2 y and ∂f ∂t (t, y) =
√1 . Thus (L3.5) has a unique solution
y
passing through y(0) = y0 for any y0 > 0. For y0 = 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) = t2 are two distinct solutions of the ODE (L3.5) for t ≥ 0 satisfying the IC y(0) = 0, see Fig. L3b.


4. Can you find any other solution to the IVP y 0 = 2 y, y(0) = 0? (hint: think of functions which
are defined piecewise).

5. Consider the IVP y 0 = 2 y, y(0) = ε > 0.
MATLAB sessions: Laboratory 3 53

0.75

0.5

0.25

0
0 0.25 0.5 0.75 1

Figure L3b: Direction field of y 0 = 2 y with two solutions satisfying y(0) = 0, namely y(t) = 0 and
y(t) = t2 . Remark: the direction field 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) = δy0 1 + √tε . How does this confirm 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 confirm 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
y
6. Determine whether the solution y(t) = 0 of the ODE y 0 = − 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 field, ode45, or (L3.4))
7. Justify why an equilibrium ye for the autonomous ODE y 0 = f (y) is called a sink if f 0 (ye ) < 0 and
a source if f 0 (ye ) > 0.
8. Consider the (autonomous) ODE y 0 = y cos y = f (y). Examine the plot of f between −2π and 2π.
Identify sources and sinks. Verify your finding by plotting the direction field.

>> y = -2*pi:pi/20:2*pi; plot(y,y.*cos(y));


8

−2

−4

−6

−8
−8 −6 −4 −2 0 2 4 6 8


9. Consider the IVP y 0 = 2 y, y(0) = 0.
(a) What is the numerical solution obtained by applying Euler’s 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 defined by
h
yn+1 = yn + (f (tn , yn ) + f (tn+1 , yn+1 )) (L3.6)
2
¡ p √ ¢2
for n = 0, 1, . . . Show that here (L3.6) yields yn+1 = h2 + yn + h yn (hint: substitute

f (t, y) = 2 y in (L3.6) and solve for yn+1 ).
(c) Plot the sequence of points (tn = nh, yn ) 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(tn ) = t2n (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

2 6
10. Consider the IVP y 0 = y 1/3 , y(0) = 0. Verify that y(t) = 9 t3/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/Saff/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 0 = f (t, y),
y(t0 ) = y0
involves y on both sides of the ODE. If an approximation φ0 of the solution y is known, then y 0 ' f (t, φ0 ).
Using the initial condition we get
Z t
y(t) ' y0 + f (s, φ0 (s)) ds (L4.1)
t0
Rt
(recall that y 0 = g(t) with y(t0 ) = y0 is equivalent to y(t) = y0 + t0 g(s) ds. Here g(t) = f (t, φ0 (t)).)
The right-hand side of (L4.1) thus defines another approximation to the function y. We call this ap-
proximation φ1 , i.e., Z t
φ1 (t) = y0 + f (s, φ0 (s)) ds. (L4.2)
t0

(L4.2) is equivalent to ½
φ01 = f (t, φ0 ),
(L4.3)
φ1 (t0 ) = y0 .
The process can be repeated, defining a sequence {φn }n≥0 of approximations to the exact solution y:
Z t
φn+1 (t) = y0 + f (s, φn (s)) ds, n = 0, 1, . . . (L4.4)
t0

or, equivalently, ½
φ0n+1 = f (t, φn ),
n = 0, 1, . . . (L4.5)
φn+1 (t0 ) = y0 ,
The iteration (L4.4/L4.5) is called Picard (fixed 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 , y0 ), and
on the choice of initial approximation φ0 (t). Without additional knowledge about the solution y(t) the
initial approximation
φ0 (t) = y0 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 t0 .
MATLAB sessions: Laboratory 4 57

One of the main applications of Picard’s method is in the proof of existence and uniqueness of the
solution for first-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 0 = y with y(0) = 1. We set φ0 (t) = 1. Then

Rt Rt
φ01 = φ0 , φ1 (0) = 1 ⇒ φ1 (t) = 1 + 0 φ0 (s) ds = 1 + 0 ds = 1 + t,
Rt Rt
φ02 = φ1 , φ2 (0) = 1 ⇒ φ2 (t) = 1 + 0 φ1 (s) ds = 1 + 0 (1 + s) ds = 1 + t + 12 t2 ,
Rt Rt
φ03 = φ2 , φ3 (0) = 1 ⇒ φ3 (t) = 1 + 0 φ2 (s) ds = 1 + 0 (1 + s + 21 s2 ) ds = 1 + 21 t2 + 61 t3 ,
Rt Rt
φ04 = φ3 , φ4 (0) = 1 ⇒ φ4 (t) = 1 + 0 φ3 (s) ds = 1 + 0 (1 + t 21 t2 + 16 t3 ) ds = 1 + 21 t2 + 61 t3 + 1 4
24 t ,
...

The pattern to the sequence of approximations is clear. For each n ≥ 0 we obtain

n
X ∞ k
X
tk t
φn (t) = → = et (Taylor series of et ).
k! k!
k=0 k=0

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 specific number
npts of points ti . The corresponding values of φn+1 (ti ) are then obtained from (L4.4) via the
update
Z ti
φ1 (ti ) = φ1 (ti−1 ) + f (s, φ0 (s)) ds, i = 1, . . . , npts, (L4.6)
ti−1

with φ1 (t0 ) = y0 . In order to determine φ2 quadl must be able to evaluate φ1 anywhere using
interpolation based on the points (ti , φ1 (ti )) obtained, via the MATLAB function interp1 (see
the help for interp1.m).

2. A more efficient 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 tj 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 first version (based on quadl) requires to set the number npts of points, while the second
version (based on ode45) does not. More importantly, the first version is less efficient, 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

s
¢
¢
s ··
φn (t) quadl φn+1 (tj ) φn+1 (t) ­
or ode45 interp1 ¶
- -
s

s
ss

Figure L4a: Numerical Picard iteration: IVP solution followed by interpolation process

picard1.m (quadl version) picard2.m (ode45 version)


function [t,y] = picard1(f,t,y,N) function [t,y] = picard2(f,t,y)
% Picard iteration using quadl % Picard iteration using ode45
TOL = 1e-6; % default, reset if desired options = odeset(’RelTol’,1e-6,’AbsTol’,1e-6);
z = y(1)*ones(size(t)); [t,y] = ode45(@fint,t([1,end]),y(1),options,f,t,y);
for k=2:N %----------------------------------------------------
z(k) = z(k-1)+quadl(@fint,t(k-1),t(k),TOL,[],f,t,y); function dydtint = fint(t,y,f,told,yold)
end % ODE rhs interpolated at t from (told,yold)
y = z; dydtint = feval(f,t,interp1(told,yold,t,’spline’));
%-------------------------------------------------------
function dydtint = fint(t,f,told,yold)
% ODE rhs interpolated at t from (told,yold)
Lab4b.m (ode45 version)
dydtint = feval(f,t,interp1(told,yold,t,’spline’));
function Lab4a
tspan = [0,3]; yspan = [0,20]; y0 = 1; N = 10;
Lab4a.m (quadl version) window = [tspan,yspan]; t = tspan;
teval = linspace(tspan(1),tspan(2),100);
function Lab4a y = feval(@init,t,y0);
tspan = [0,3]; yspan = [0,20]; y0 = 1; N = 10; plot(t,y,’r’,’LineWidth’,2);
window = [tspan,yspan]; t = tspan; hold on;
npts = 100; % #pts for integration for n = 1:N
t = linspace(tspan(1),tspan(2),npts); [t,y] = picard2(@f,t,y);
y = feval(@init,t,y0); yint = interp1(t,y,teval,’spline’);
plot(t,y,’r’,’LineWidth’,2); plot(teval,yint,’r’,’LineWidth’,2);
hold on; end
for n = 1:N dirfield(@f,window,’arrow’); % direction field, see Lab1
[t,y] = picard1(@f,t,y,npts); [t,y] = ode45(@f,tspan,y0); % "exact" solution
plot(t,yint,’r’,’LineWidth’,2); plot(t,y,’b’,’LineWidth’,2); % plot "exact" solution
end hold off
dirfield(@f,window,’arrow’); % direction field, see Lab1 axis(window)
[t,y] = ode45(@f,tspan,y0); % "exact" solution %---------------------------------------------------
plot(t,y,’b’,’LineWidth’,2); % plot "exact" solution function dydt = f(t,y) % ODE
hold off dydt = y;
axis(window) %---------------------------------------------------
%--------------------------------------------------- function y = init(t,y0)
function dydt = f(t,y) % ODE % initialization for Picard iteration.
dydt = y; y = y0*ones(size(t)); % standard. If modified, make
%--------------------------------------------------- % sure the new function satisfies the IC
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 field (see Laboratory
1) has been superposed to check the validity of the approximation.

1. Reproduce Fig. L4b using both versions of picard. Experiment with different initial functions
φ0 (t) (e.g. t, t2 , . . .). Compare the iterations obtained with φ0 (t) = 1 + t to those obtained with
φ0 (t) = 1.

2. Consider the IVP y 0 = −y, y(0) = 1.


MATLAB sessions: Laboratory 4 59

20

18

16

14

12

10

0
0 0.5 1 1.5 2 2.5 3

Figure L4b: Picard iterates φ1 , . . . , φ10 starting with φ0 (t) = 1 for the IVP y 0 = 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 }n≥0 ?
(b) Use the ode45 version of the MATLAB implementation of Picard’s iteration to obtain the
first 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 0 = 2t − y 2 , y(0) = 0, is known to have a solution for all t > 0.
(a) Determine algebraically (as in page 57) the first two iterates φ1 and φ2 .
(b) Use the ode45 version of the MATLAB implementation of Picard’s iteration starting with
φ0 (t) = 1 to obtain the first 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 first 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 0 = 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) = y0 is a (constant) solution to the IVP y 0 = f (t, y), y(0) = y0 , then φn (t) = y0
for n > 0 if φ0 (t) = y0 . More generally, show that if y(t) is a (possibly non-constant) solution to
the IVP y 0 = f (t, y), y(0) = y0 , 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 0 = 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 Picard’s iteration starting with
φ0 (t) = t to obtain the first 20 iterates in the window 0 ≤ t ≤ 1 (use the range 0 ≤ y ≤ 1 for
plotting).
7. Consider the IVP y 0 = 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 Picard’s iteration starting with
φ0 (t) = 1 to obtain the first 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 confirm your answers from the above parts.
MATLAB sessions: Laboratory 5 61

Laboratory 5
Applications of First-Order Differential Equations
(Ch. 3 of the Nagle/Saff/Snider text)

First-order differential 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 differential equations in modelling changes in population by means of the exponential, logistic,
and modified logistic population models.

2. Use differential equations in modelling various other growth and decay problems.

3. Use differential 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
= rN. (L5.1)
dt
Separating variables and solving for N (t) with initial value N (t0 ) = N0 yields the exponential function
N (t) = N (t0 )er(t−t0 ) . The proportionality constant r is the difference 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 Nmax denote the maximum
sustainable population size (also called carrying capacity) of the habitat of study. Then Nmax − N is the
number of new individuals that the habitat can accept and Nmax −N
Nmax the percentage of Nmax available for
population growth. As the population approaches the carrying capacity Nmax , the percentage of Nmax
available for growth is small as a result of overcrowding and more competition for limited resources.
On the other hand the percentage Nmax −N
Nmax → 1 for population sizes well below the carrying capacity.
Formally the logistic population growth is then modelled by the ODE
µ ¶
dN Nmax − N N
= rN = rN 1− = rN − cN 2 (L5.2)
dt Nmax Nmax

with c = r/Nmax . 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

Modified 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 Nmin , the inability to find a suitable mate leads to the extinction of the species.
The modified logistic equation (also called Nagumo equation) is
µ ¶µ ¶
dN N N
= rN 1 − −1 . (L5.3)
dt Nmax Nmin

Note that dN/dt < 0 for 0 < N < Nmin .

Effect 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 N
= rN 1 − − α.
dt Nmax

Problems
1. Generate the direction fields of the exponential, logistic, and modified logistic models for population
growth and record any observable differences. Use Nmax = 20, Nmin = 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 find a numerical answer.

3. Suppose that the population of a species of fish in a certain lake is growing according to a logistic
model with r = 0.3 and Nmax = 3000. Assume that initially there are 2500 fishes of that species
in the lake. Determine the correct IVP for each of the scenarios below and in each case determine
from the direction field of the differential equation the long term behavior of the fish population.

(a) each year 150 fishes 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 fishes are harvested from the lake.
(c) what is the maximum safe fixed amount to harvest each year in order to assure that there
will always be some fish 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

65

60

55

50

45

40

35

30
0 2 4 6 8 10 12 14

(a) Which of the three population models (exponential, logistic, modified 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 ti = 1, 2, . . . we thus have two values for the population: the data Ni from the
above table and the value y(ti ) computed use ode45 for a specific guess of the parameter(s).
X13
Evaluate the quantity (yi − y(ti ))2 . If your result is much larger than 0.878 adjust your
i=1
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


Differential 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. Newton’s law of cooling states that the rate dT dt at which the temperature T of an object
changes with time is proportional to the difference of temperature between the object and the
ambient medium. Mathematically we write
dT ¡ ¢
= k Tair − T .
dt
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
first-order rate of change).

s a - i b - r

Accordingly, the following equations hold:

ds di dr
= −asi, = asi − bi, = bi. (L5.4)
dt dt dt
d
Note that dt (s + i + r) = 0, i.e., s + i + r = cst = N . From (L5.4) one easily obtain

di asi − bi b/a
= = − 1, (L5.5)
ds −asi s
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(s0 ) = i0 .


(b) Graph the solution for particular choices of b/a, s0 , and i0 . 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 filled 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 flowing out at a rate of 5 liters/min.
rin = 5 `/m -
cin = 2 kg/`

volume
V (t)
concentration
c(t)

- rout = 5 `/m
cout = 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
rin , rout , cin , 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 flows 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 m2 , the leak is at the bottom of
the tank, and the rate of flow 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 rin , rout , 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 Differential Equations
(Project B of Ch. 2/Ch. 3 of the Nagle/Saff/Snider text)

In this laboratory we will examine further applications of first-order differential equations. These sup-
plement the applications given in the previous lab. Applications included are the snowplow problem,
aircraft guidance, and uses of Newton’s law of cooling in the heating and cooling of buildings.

The Snowplow Problem


(see page 84 of the Nagle/Saff/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 specifies 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)
s
6
1 P.M (t = 4)
-p

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 dp b
= a and = (L6.1)
dt dt s
where a and b are positive constants.

1. Solve (L6.1) first for s = s(t), then for p = p(t) using appropriate initial conditions.

2. Show that T satisfies the nonlinear equation


¡ 2
¢
ln 1 + T 2
¡ 4
¢= .
ln 1 + T
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)

b
At what time (in the form ?:?? A.M.) did it start to snow? What is the value of the ratio 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 differential equation model similar to (L6.1) for p = p(t).

5. Solve the model and show that T satisfies the nonlinear equation
¡ ¢
ln 1 + T2 − ln(1 + 2α) 2
¡ ¢ = .
ln 1 + T4 − ln(1 + 4α) 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/Saff/Snider text)

An aircraft flying under the guidance of a nondirectional beacon (a fixed 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.

6
y

T ©©¡
© ¡
©
¼
¡
W¡ A
6 W
¡
ª 6
¦ x-
68 MATLAB sessions: Laboratory 6

We place the start of the flight at (2,0) and the destination at (0,0). Let
" dx # · ¸ · ¸
dt 0 x
T = dy , W = , A=α
w y
dt

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) satisfies the ODE
p
dy y x2 + y 2
= −γ
dx x 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?


dy
11. For small x show that the ODE becomes dx ' (1 − γ) xy . Deduce that y(x) ' x1−γ 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/Saff/Snider text)

A model for the change in temperature in a building is given by the ODE


dT
= k(Tout − T ) + ku (T ∗ − T ). (L6.2)
dt
The constants k and ku are proportionality constants in Newton’s law of cooling, Tout 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
Tout = 80 − 15 cos .
12

The temperature T ∗ is set such that k(T̄out − Td ) + ku (T ∗ − Td ) = 0 for a desired temperature Td , where
T̄out is the daily average outside temperature.
12. Show that (L6.2) can be written
dT
= k(Tout − T̄out ) + (k + ku )(Td − T ).
dt
MATLAB sessions: Laboratory 6 69

Two solutions corresponding to k = 0.5 and k = 0.25 (units/hour) are shown in Fig. 3 (ku =
1 unit/hour, Td = 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);

80
k=0.5
k=0.25
79

78

77

76

75

74

73

72

71

70
0 6 12 18 24 30 36 42 48

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
= k(Tout − T ) + U (L6.3)
dt
is obtained with constant rates U = 8 units/hour of heat if T < Td and U = −6 units/hour of cooling
if T > Td + 1. In between Td and Td + 1 there is no artificial 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 Td , or cool it
down to −dT below Td . 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

95
outside
first model
improved model

90

85

80

75

70

65
0 6 12 18 24 30 36 42 48

Figure L6b: Improved vs basic temperature control (k = 0.25).

16. Reduce the size of U to see the effect. 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 effect on the graph.
R 48 R 48
18. (hard) The energy consumed is E1 = 0 ku |T ∗ − T (t)|dt for the first model and E2 = 0 |U |dt
for the second. Which strategy uses the most energy?
72 MATLAB sessions: Laboratory 7

Laboratory 7
Implementing Higher-Order Differential Equations
(Ch. 4, 6 of the Nagle/Saff/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 first-order by rewriting the ODE in the form of
a system of first order ODEs.
Our objectives in this laboratory are as follows:
1. Learn how to reduce a higher-order IVP to a first-order system
2. Learn how to implement a higher-order/system ODE in MATLAB using ode45.m and euler.m.
3. Get some proficiency in analyzing and comparing solutions for different but similar problems.

Reducing a Higher-Order ODE


(see §5.2, page 243, of the Nagle/Saff/Snider text)

Let’s start with an example. Consider the IVP

d2 y dy dy
+4 + 3y = cos t, with y(0) = −1, (0) = 0. (L7.1)
dt2 dt dt
dy
To reduce the order of the ODE we introduce the intermediate unknown function v = dt . As a result
dv d2 y dv
dt = so that the ODE can be written
dt2 dt+ 4v + 3y = t + cos t. This equation only involves first-
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
( dy
d2 y dy dt = v,
2
+4 + 3y = cos t ⇔ (L7.2)
dt dt dv
= cos t − 4v − 3y.
dt

Initial conditions from (L7.1) must also be transformed into initial conditions for y and v. Simply,
(
dy y(0) = −1,
y(0) = −1, (0) = 0 ⇔ (L7.3)
dt v(0) = 0.

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 specified 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 figure window 1, and the phase plot
showing v vs y is done in the figure window 2.

0.8 1
y(t)
v(t)=y’(t)
0.6
0.8

0.4
0.6

0.2

0.4
0
v=y’

−0.2 0.2

−0.4
0

−0.6
−0.2

−0.8

−0.4
−1 −1 −0.8 −0.6 −0.4 −0.2 0 0.2 0.4
0 2 4 6 8 10 12 y

Figure L7a: Time series y = y(t) and v = v(t) = y 0 (t) (left), and phase plot v = y 0 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 00 + 2y 0 + y = cos t with y(0) = y 0 (0) = 0. Plot both time series of y and y 0
and the phase plot y 0 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 modification to find 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.4 1
ode45 ode45
Euler Euler

0.2 0.8

0 0.6

0.4
−0.2
v=y’

0.2
−0.4

0
−0.6

−0.2
−0.8

−0.4
−1 −1 −0.8 −0.6 −0.4 −0.2 0 0.2 0.4
0 2 4 6 8 10 12 y

Figure L7b: Time series y = y(t) (left) and phase plane v = y 0 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 difficulty from an implementation point of view (they
may present new numerical challenges for integration routines like ode45). As an example consider the
modified problem
d2 y dy dy
2
+ 4y 2 + 3y = cos t, with y(0) = −1, (0) = 0. (L7.4)
dt dt dt
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 modified (same initial
conditions) while the ODE definition 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

2 2
y(t)
v(t)=y’(t)

1.5 1.5

1 1

0.5
0.5

v=y’
0
0

−0.5
−0.5

−1
−1

−1.5
−1.5 −1 −0.8 −0.6 −0.4 −0.2 0 0.2 0.4 0.6 0.8
0 2 4 6 8 10 12 y

Figure L7c: Time series y = y(t) and v = v(t) = y 0 (t) (left), and phase plot v = y 0 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

d2 y dy dy
+ 4|y| + 3y = cos t, with y(0) = −1, (0) = 0
dt2 dt dt
in the interval 0 ≤ t ≤ 12. Is the behavior of the solution significantly different 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

d2 y dy dy
+ 4y + 3y = cos t, with y(0) = −1, (0) = 0
dt2 dt dt
in the interval 0 ≤ t ≤ 12. Is the behavior of the solution significantly different from that of the
solution of (L7.4)? Comment.

A Third-Order Problem
Consider the third-order IVP
µ ¶2
d3 y 2
2d y dy dy dy d2 y
+ 4y + 8y +3 = − sin t, with y(0) = −1, (0) = 0, 2 (0) = 4. (L7.5)
dt3 dt2 dt dt dt dt
dy dy 2 dv dw d3 y 2 2
Introducing v = dt and w = dt2 we obtain dt = w and dt = dt3 = − sin t−4y w −8yv −3v. Moreover,
2
dy
v(0) = dt (0) = 0 and w(0) = ddt2y (0) = 4. Thus (L7.5) is equivalent to
 dy 

 dt = v,  y(0) = −1,
 
dv v(0) = 0,
dt = w,
with (L7.6)

 

 dw 2 2 w(0) = 4.
dt = − sin t − 4y w − 8yv − 3v

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]).

2
y(t)
v(t)=y’(t)
w(t)=y’’
1.5

0.5 2
w=y’’

0 −2

−4
2 0.8
−0.5 0.6
1.5
0.4
1
0.2
0.5 0
−1
0 −0.2
−0.4
−0.5
−0.6
−1 −0.8
−1.5 v=y’ y
0 2 4 6 8 10 12 −1.5 −1

Figure L7d: Time series y = y(t), v = v(t) = y 0 (t), and w = w(t) = y 0 (t) (left), and 3D phase plot v = y 0
vs. y vs w = y 00 for (L7.5) (rotated with view = [-45,60]).

7. (a) Compare the output of Figs L7c and L7d. What do you notice?
(b) Differentiate the ODE in (L7.4) and compare to the ODE in (L7.5).
(c) Explain why the solution of (L7.4) also satisfies the initial conditions in (L7.5).
(d) Solve the problems (L7.4) and (L7.5) using Euler’s 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 first-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 first-order ODEs consider for example the choice v = dydt + y, i.e.,
dy
dt = v − y. Then
µ ¶
dv d2 y dy dy dy
= 2 + = cos t − 4 − 3y + = cos t − 3(v − y) − 3y = cos t − 3v. (L7.7)
dt dt dt dt dt
MATLAB sessions: Laboratory 7 77

To get an initial condition for v substitute t = 0 in the definition of v:


dy
v(0) = (0) + y(0) = 0 + (−1) = −1. (L7.8)
dt
Thus ( (
dy
dt = v − y, y(0) = −1,
(L7.1) ⇔ with (L7.9)
dv v(0) = −1.
dt = cos t − 3v
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 first 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 0 .
dy
9. Is there any other value of r such that the choice v = 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/Saff/Snider text)

In this laboratory we will examine harmonic oscillation. We will model the motion of a mass-spring
system with differential equations.
Our objectives are as follows:
1. Determine the effect of parameters on the solutions of differential equations.
2. Determine the behavior of the mass-spring system from the graph of the solution.
3. Determine the effect 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 first principle of mechanics we then obtain

mg + −k(` − `0 ) = 0. (L8.1)
|{z} | {z }
downward weight force upward tension force

The term g measures the gravitational acceleration (g ' 9.8m/s2 ' 32f t/s2 ). The quantity k is a spring
constant measuring its stiffness. 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

d2 (` + y) d2 y
mg + −k(` + y − `0 ) = m , i.e., m + ky = 0 (L8.2)
|{z} | {z } | dt
2
{z } dt2
weight upward tension force
acceleration of mass

using (L8.1). This ODE is second-order.

`0 k

y
m

(a) (b) (c) (d)


MATLAB sessions: Laboratory 8 79

Equation (L8.2) is rewritten


d2 y
+ ω2 y = 0 (L8.3)
dt2
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) = 0 (i.e., the mass is initially stretched downward 10cms
and released, see setting (c) in figure) is obtained by first reducing the ODE to first-order ODEs (see
Laboratory 7).
Let v = y 0 . Then v 0 = y 00 = −ω 2 y = −4y. Also v(0) = y 0 (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 different values of ω need to
be compared in a single MATLAB figure window.

0.2

0.15

0.1

0.05

−0.05

−0.1

−0.15

−0.2
0 1 2 3 4 5 6 7 8 9 10

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 stiffness k of the spring affect the motion?
2. (a) Plot the quantity E = 12 mv 2 + 12 ky 2 as a function of time. What do you observe?
dE
(b) Show analytically that 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 effects (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

d2 y dy d2 y dy
m +γ + ky = 0 or +c + ω2 y = 0 (L8.4)
dt2 dt dt2 dt
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 t1 will the mass-spring system satisfy |y(t)| > 0.01 for all t > t1 ? You
can answer the question either by magnifying the MATLAB figure 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 γ affect 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.2
y(t)
v(t)=y’(t)

0.15

0.1

0.05

−0.05

−0.1

−0.15

−0.2
0 1 2 3 4 5 6 7 8 9 10

Figure L8b: Damped harmonic motion

4. (a) Plot the quantity E = 12 mv 2 + 12 ky 2 as a function of time. What do you observe?


dE dE
(b) Show analytically that dt < 0 for γ > 0 while 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 coefficient γ, the spring constant k, the initial condi-
tions y(0) and y 0 (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 predefined 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 affect 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/Saff/Snider text)

In this laboratory we model the motion of a (simple) pendulum with a second-order differential equation.
A mass m is attached to a rigid rod rotating around a fixed 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.
The position of the mass m is (x, y) = (` sin θ, ` cos θ). The first
principle of mechanics states that the acceleration vector A is
the sum of all forces applied to the mass, namely the weight
qc - W, the tension in the rod T, and the friction force F opposite
@. x
.......
to the movement and proportional to the velocity of the mass.
...............@
θ @` µ
¡ Thus
@ ... ¡ A=W+F+T (L9.1)
...
@
I ... ¡

@T
...
... ¡ A
.. with
....
.
@ .........¡ ..
.
· ¸ · ¸ µ ¶2 · ¸
@
@y ...¡
.
.... d2 x d2 θ cos θ dθ sin θ
....
.
.
m A=m 2 = m` 2 − m` ,
......¡
.......
...... dt y dt − sin θ dt cos θ
.......
........ ¡ ª
..
..
..
........
...........
............ F · ¸ · ¸ · ¸
.......................................................................... 0 d x dθ cos θ
W W = , F = −γ = −γ` ,
mg dt y dt − sin θ
(g ' 9.8 m/s2 ' 32 f t/s2 ) and
y? ? · ¸ · ¸
x sin θ
T∝ ∝
y cos θ

(only ·the direction


¸ of T is known, not the magnitude).
cos θ
When taking the dot product of (L9.1) with the contribution of T disappears (this amounts
− sin θ
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
d2 θ dθ d2 θ dθ
m` = −mg sin θ − γ` , or + c + ω 2 sin θ = 0 (L9.2)
dt2 dt dt2 dt
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 effect of variations in the parameters in the solution.
2. Determine the effect of “linearization” of the differential equation.

The Undamped Case


Let’s first assume that c = 0 (i.e., γ = 0). We solve the ODE (L9.2) subject to initial conditions
θ(0) = 45 degrees and θ0 (0) = 1 rad/s, assuming ` = 0.5 m. The ODE is first reduced to a set of two
first-order ODEs
dθ dv
= v, = −ω 2 sin θ (L9.3)
dt dt
with v(0) = θ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

50

40

30

20

10

−10

−20

−30

−40

−50
0 2 4 6 8 10 12 14 16 18 20

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 affect 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
modified compared to the previous situation? The following graph shows the case v(0) = 8.17 rd/s.
MATLAB sessions: Laboratory 9 85

200

150

100

50

−50

−100

−150

−200
0 2 4 6 8 10 12 14 16 18 20

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


22
(b) θ(0) = 7 rad, θ0 (0) = 0 rad/s.
(c) θ(0) = π rad, θ0 (0) = 30 rad/s.
(d) θ(0) = 2π rad, θ0 (0) = 1 rad/s.
(e) θ(0) = 10π rad, θ0 (0) = 0 rad/s.
220
(f) θ(0) = 7 rad, θ0 (0) = 0 rad/s.
(g) θ(0) = −7π rad, θ0 (0) = 0.03 rad/s.
(h) θ(0) = −7π rad, θ0 (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?
¡ dθ ¢2
5. (a) Plot the quantity E = 12 m` dt + mg(1 − cos θ) as a function of time. What do you observe?
dE
(b) Show analytically that dt = 0.
(c) Plot v vs θ (phase plot). How does the curve behave?
86 MATLAB sessions: Laboratory 9

The Linearized Case


Let’s know examine what happens when we substitute θ for sin θ in (L9.2). The new equation for θ is
thus
d2 θ
+ ω 2 θ = 0. (L9.4)
dt2

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 (0) = 2 rad/s.


(b) θ(0) = 0 degree, θ0 (0) = 50 rad/s.
(c) θ(0) = 10 degrees, θ0 (0) = 8 rad/s.
(d) θ(0) = 45 degrees, θ0 (0) = 8.17 rad/s.
(e) θ(0) = 45 degrees, θ0 (0) = 8.18 rad/s.
(f) θ(0) = 180 degrees, θ0 (0) = 30 rad/s.
(g) θ(0) = 360 degrees, θ0 (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 significant discrepancies between original and linearized
cases? Can you explain why?

With Damping Present


Now consider a small damping coefficient c in the original “non-linearized” equation (L9.2) and observe
the effect.

7. First reduce the ODE (L9.2) to a system of two first-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 figures 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 (0) = 1 rad/s.


50

40

30

20

10

−10

−20

−30

−40
0 2 4 6 8 10 12 14 16 18 20

(b) θ(0) = 180 degrees, θ0 (0) = 0 rad/s.


200

150

100

50

−50

−100
0 2 4 6 8 10 12 14 16 18 20

(c) θ(0) = 180 degrees, θ0 (0) = 10 rad/s.


550

500

450

400

350

300

250

200

150
0 2 4 6 8 10 12 14 16 18 20
88 MATLAB sessions: Laboratory 9

8. The Poe pendulum


(Poe’s Pendulum by Borelli, Coleman & Hobson, Mathematics Magazine, 58(2) (1985) 78-83)
Do problem 7 first. 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

d2 θ dθ ω2
+ c + sin θ = 0 (L9.5)
dt2 dt 1 + αt
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 (0) = 1 rad/s? Make sure
that you integrate the differential equation over a sufficiently large time interval.
MATLAB sessions: Laboratory 10 89

Laboratory 10
Forced Equations and Resonance
(§4.9 of the Nagle/Saff/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

d2 y dy
+c + ω 2 y = sin Ωt. (L10.1)
dt2 dt
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
1 60
frequency ω (in radians per second = 2π rotation per second = 2π rotations per minute, or RPM) of
the plate holding the mass-spring system. All physical constants are assumed to be positive.
When 2c < ω the general solution of (L10.1) is
Ãr !
c2
− 12 ct
y(t) = ae sin t ω 2 − + φ + A sin (Ωt + ϕ) (L10.2)
4

with
1
A= q , (L10.3)
2
(ω 2 − Ω2 ) + c2 Ω2
¡ ¢
sin ϕ = −cΩA, cos ϕ = ω 2 − Ω2 A, (L10.4)
and a and φ are determined from the initial conditions (see §4.9 of the Nagle/Saff/Snider text). The
first 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 first 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 effect of the forcing term on the behavior of the solution for different 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 fixed. Initial conditions are set to 0. For each value of Ω, the
amplitude A can be obtained numerically by taking half the difference between the highs and the lows
of the solution computed with a MATLAB ODE solver after a sufficiently 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 defines a time t1 after which we think the contribution of
the first term in (L10.2) has become negligible compared to the second term. This depends of course
1
on the parameter values, in particular c. With c = 1 we obtain e− 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 difference between the max and the min
values. This value is compared to the theoretical value (L10.3).

0.6

0.4

0.2

0
y

−0.2

−0.4

−0.6

−0.8
0 5 10 15 20 25 30 35 40 45 50

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 ϕ defined by (L10.4)?
MATLAB sessions: Laboratory 10 91

(b) Subtract the quantity A sin (Ω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?
1
(c) Divide the resulting function obtained in (b) by e− 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) = 0. The


previous problem determined A for a specific 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 ];
0.55

0.5

0.45

0.4

0.35
A

0.3

0.25

0.2

0.15
1 1.2 1.4 1.6 1.8 2 2.2 2.4 2.6 2.8 3

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: differentiate...) Are the results affected by changes in the initial
conditions?

Resonance

We now investigate what happens to the solution (L10.2), and more specifically 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.


30
computed numerically
theoretical

25

20

15
A

10

0
1 1.2 1.4 1.6 1.8 2 2.2 2.4 2.6 2.8 3

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 different 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

2.5

1.5

0.5

0
y

−0.5

−1

−1.5

−2

−2.5
0 10 20 30 40 50 60 70 80 90 100

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/Saff/Snider text)

In this laboratory we consider two-dimensional linear systems of the form



 dx = ax + by,


dt
(L11.1)

 dy
 = cx + dy
dt
where a, b, c, and d are real constants. The system (L11.1) is written in matrix form
· ¸ · ¸
dx x a b
= Ax with x = and A = . (L11.2)
dt y c d
The objectives of this laboratory are as follows.
1. Learn how to use MATLAB to find 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/Saff/Snider text)
· ¸
1 4
Consider the matrix A = . The eigenvalues are the roots of the characteristic equation p(λ) =
2 −1
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 coefficients. 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,
¸ find the set of vectors x satisfying (A − λI)x = 0 (I is the 2 × 2 identity
1 0
matrix I = ). This set is called the nullspace of the matrix A − λI. This can be done via
0 1
MATLAB’s 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
· ¸
0.8944
Thus x = is an eigenvector of A associated to eigenvalue λ = 3 (in fact any nonzero multiple of
0.4472
this vector is also an eigenvector associated to eigenvalue 3). A quick numerical verification 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 efficient 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
first one is a matrix S whose columns are the eigenvectors x1 and x2 of A, i.e., S = x1 |x2 . The
second matrix is a diagonal
· matrix
¸ Λ (read “lambda”) whose diagonal coefficients are the corresponding
λ1 0
eigenvalues, i.e., Λ = . In this case the eigenvalues are referenced in MATLAB as Lambda(1,1)
0 λ2
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 find 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 differential system (L11.2) (i.e., (L11.1)). From the theory we know
that the solution is
x(t) = C1 eλ1 t x1 + C2 eλ2 t x2 (L11.3)
where C1 and C2 are constants defined from the initial conditions. At t = 0 we obtain
· ¸ · ¸
£ ¤ C1 C
x(0) = C1 x1 + C2 x2 = x1 |x2 =S 1 . (L11.4)
C2 C2
Given the initial vector x(0), the constants
· ¸ C1 and C2 can be obtained by solving the system (L11.4).
1
If x(0) = 1 and y(0) = 0 then x(0) = .
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
dy
A phase plot is a direction field of the ODE dx = . . .. From (L11.1) we obtain
dy dy/dt cx + dy
= = .
dx dx/dt 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 ±x1 and ±x2 ) 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 file dirfield.m page 38.
5. Complete the direction of the flow 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 different initial
conditions to confirm your choice.
MATLAB sessions: Laboratory 11 97

1.5

0.5

−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 specified window? Can
you select a window so that these remarks disappear. You may need to refer to the file 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
x1 , so that a matrix S cannot be constructed as above. Instead we find a vector y satisfying

(A − λ1 I)y = x1 . (L11.5)

The vector y is called a generalized eigenvector. It can be shown that (L11.5) always has infinitely many
solutions, defined up to a multiple of the eigenvector x1 . The general solution of (L11.2) is then formed
as the combination
x(t) = C1 eλ1 t x1 + C2 eλ1 t (tx1 + y) , (L11.6)
where C1 and C2 are constants defined from
· the initial
¸ conditions.
−1 1
For example consider the matrix A = . The eigenvalues/eigenvector of A are obtained
0 −1
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 x1 and λ1 as the first column of S and the first diagonal coefficient of Lambda,
respectively. Compute the vector y from (L11.5) and form the solution (L11.6), with constants
C1 and C2 computed from initial conditions x(0) = 1 and y(0) = 0. Compare the solution to
the direct solution obtained with ode45.
dx dy
(b) The IVP solved in this case is = −x + y, = −y, with x(0) = 1 and y(0) = 0. First
dt dt
dx
solve explicitly for y = y(t) and substitute in the ODE for , then solve for x = x(t). Does
dt
the solution match the results obtained in (a)?

9. Find another matrix A with double eigenvalue λ1 = λ2 = −1 and a single eigenvector (direction)
x1 . 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

1.5

0.5

−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 coefficients. 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)?
−1 6
Let A = . As before we first compute the eigenvalues and eigenvectors of A:
−4 6
>> 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

1.5

0.5

−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 flow 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 different 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 Euler’s formula eit = cos t + i sin t.

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.
· ¸ · ¸
2 −6 1
(a) A = , x(0) = .
2 1 0
   
−2 1 0 1
(b) A = −1 0 2, x(0) = 1. (Use plot3 to plot the solution)
−1 1 0 2
   
−2 3 0 1
(c) A = −1 0 2, x(0) = 1. (Use plot3 to plot the solution)
−1 1 0 2

14. Convert the second-order linear ODE y 00 +3y 0 +2y = 0 into a set of two first 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 → ∞?
· ¸
2 −1
15. Consider the ODE system (L11.2) with A = . Compute eigenvalues, eigenvectors and
−1 2
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) = etA x(0),

where etA is the matrix exponential of the·matrix


¸ tA. Use the MATLAB function expm to obtain
1
the solution with initial condition x(0) = . Compare with the solution computed by applying
0
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/Saff/Snider text)

In this laboratory we discuss several improvements on Euler’s and improved Euler’s methods for solving
scalar and systems of differential equations, and introduce the notion of order of a numerical method.
This is done in the context of a simple first-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 fixed-step numerical methods which is more accurate than Euler’s 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 first step of Euler’s method for solving the IVP y 0 = f (t, y) with y(t0 ) = y0 can be interpreted by
considering the truncation of the Taylor series expansion to first-order terms, namely

y(t1 ) = y(t0 + h)
' y(t0 ) + hy 0 (t0 )
= y0 + hf (t0 , y(t0 ))
= y0 + hf (t0 , y0 ) ≡ y1 .

If instead we truncate the expansion after two terms we obtain

y(t1 ) = y(t0 + h)
h2 00
' y(t0 ) + hy 0 (t0 ) + y (t0 )
2 µ ¶
h2 ∂f ∂f
= y0 + hf (t0 , y0 ) + (t0 , y0 ) + (t0 , y0 )f (t0 , y0 ) ≡ y1 . (L12.1)
2 ∂t ∂t
Equation (L12.1) defines the first 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 Taylor’s 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 0 = −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 Euler’s method and
Taylor’s 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 Chp what is approximately the value
of p for Euler’s method? for Taylor’s 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 Euler’s method? How
does this number compare with the number of steps required for Taylor’s method?

The Taylor method of order 2 appears superior to Euler’s method. However, for problems where f (t, y)
is complicated or discontinuous, the gain in efficiency 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 flying under the guidance of a nondirectional beacon was described in
Laboratory 6, page 67. The equations defining the rate of change of the position of the aircraft are given
by

 dx ax

 = −p
 dt x2 + y 2
à ! (L12.2)

 dy y

 = a γ − p
dt x2 + y 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 final 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. (Kepler’s problem) The planar movement of a planet in the gravitational field of the sun (or a
satellite around the earth) is described by the second-order system
 2
 d x x
 =− 3 p
dt2 r with r= x2 + y 2 . (L12.3)
2

 d y =−y
dt2 r3

The initial conditions used for this problem are x(0) = 1, y(0) = 0, x0 (0) = 0, and y 0 (0) = 0.8.

(a) Reduce the system of ODEs (L12.3) to a system of 4 first-order ODEs. Specify appropriate
initial conditions.
(b) Write a file 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 dx
dt − y 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 defined by the set of differential
equations
 2

 d x dy x+a x−1+a ½ p
 =x+2 − (1 − a) 3 − a
dt2 dt r1 r23 r1 = p(x + a)2 + y 2
2 with

 d y dx y y r2 = (x − 1 + a)2 + y 2
 =y−2 − (1 − a) 3 − a 3
dt2 dt r1 r2

with a = 0.012277471. The initial conditions are x(0) = 0.994, y(0) = 0, x0 (0) = 0 and y 0 (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

0.5

Moon
0
Earth

−0.5

−1

−1.5
−1.5 −1 −0.5 0 0.5 1 1.5
106 MATLAB sessions: Laboratory 12

14. (Lorenz system) The Lorenz equations




 dx

 = 10(y − x)
 dt

dy
= 28x − y − xz

 dt

 dz 8

 = xy − z
dt 3
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 modified 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 fly. In addition, you can change
parameters and configuration and immediately see what happens.
Our objectives are as follows:

1. learn how to build simple differential 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 file spring1.mdl), of clicking either on the file icon or the file 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 defining the Sine Wave can be obtained by clicking on the Sine Wave block. The four
parameters defining 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. Let’s 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 0 is
the output of the first block and
z = y 00 . (L13.2)
Following now the feedback loops above and below, we encounter a Gain block of the form (here the
direction has been flipped). These blocks are simply multipliers by the indicated value. Note that the
Gain block above has input y 0 while the Gain block at the bottom has input y. We have thus

z1 = 4 × y = 4y and z2 = 1 × y 0 = y 0 . (L13.3)

Combining equations (L13.1), (L13.2), and (L13.3) we then obtain

y 00 = cos t − 4y − y 0 , i.e., y 00 + y 0 + 4y = cos t. (L13.4)

Equation (L13.4) is a second-order linear differential equation modelling the displacement of a mass
m = 1 unit attached to a spring with constant k = 4 in a viscous environment with friction coefficient
γ = 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) = 0 (left integrator).

The output Scope input port is y. To visualize this output first 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 different blocks in the model by dragging them with the mouse.
2. Experiment with changing the values of the parameters in the different blocks of the spring1
model.
1
3. Why is the integrator block labelled with the symbol s? Hint: think of the connection between
the Laplace transforms of y 0 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
final 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 different.
5. Modify your SIMULINK model to represent the ODE y 00 + y 0 + 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 differential equation (L13.4). Defining
· ¸
y
x= 0
y
we obtain · 0¸ · ¸ · ¸· ¸ · ¸
dx y y0 0 1 y 0
= 00 = = + = Ax + b (L13.5)
dt y cos t − 4y − y 0 −4 −1 y 0 cos t
· ¸ · ¸
0 1 0
with A = and b = . Equation (L13.5) defines a first-order system. The initial condition
−4 −1 cos t
for x is · ¸ · ¸
y(0) 1
x(0) = 0 = .
y (0) 0

Because (L13.5) is first-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 amplification 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 0 .

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
= Ax + B cos t
dt
y = Cx + D cos 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/Saff/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 difficulties 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
Z ∞
Y (s) = f (t)e−st dt. (L14.1)
0

The integral in (L14.1)


1. converges at t = 0 if
C
|f (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 first transforming (L14.1) using the change of variable u = e−t , i.e., t = − ln u, so that
Z 1
Y (s) = f (− ln u)us−1 du. (L14.4)
0

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 defined 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 differ too much a warning message is displayed.
For the above example (f (t) = sin t) 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 us−1 is large for u ' 0, in which
case t = − ln u ' ∞. Since f (t) = sin t 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) = sin t 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) = et 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
1 − e−t
transform. For example consider the function f (t) = √ . Note that f ' √1πt for t ' 0 so that
t πt
(L14.2) holds with ρ = 12 and C = 2, and (L14.3) is satisfied 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 difficulty 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
−t
as follows. Consider the function g(t) = 1−e

π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) = √1s , 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

P (s) −ct
F (s) = e (L14.5)
Q(s)

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
P (s)
H(t − c)f (t − c) is F (s)e−ct ). The fraction 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 specified 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) = 5s(2s+1)(s+3)
3 +2s2 +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

P (s)
writes the rational function Q(s) in a nicer form to verify that P and Q have been entered correctly.

1.5

0.5
f(t)

−0.5

−1

−1.5
0 20 40 60 80 100 120
t

(2s+1)(s+3) −10s
Figure L14a: Inverse Laplace transform of F (s) = 5s3 +2s2 +3s+1 e .

F 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
(2s+1)(s+3) −10s
For the function F (s) = 5s3 +2s2 +3s+1 e 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) =
5s3 +2s2 +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.

F 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) = 1s , let alone to more complex functions. It is sufficient 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 sufficient 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);

1.5

0.5
f(t)

−0.5

−1

−1.5
0 20 40 60 80 100 120
t

(2s+1)(s+3) −10s
Figure L14b: Numerical inverse Laplace transform of F (s) = 5s3 +2s2 +3s+1 e 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: lims→∞ sF (s) = limt→0 f (t) for F ).
5. Determine the inverse transform of the following functions using invlap and, when possible,
InvLaplace. Comment on the results.
1 e−s e−2s
(a) F (s) = (e) F (s) = +
(s + 1)(s + 2) s+1 s+2
1 1
(b) F (s) = (f) F (s) =
s2 +1 (s + 1)(1 + e−s )
µ ¶
e−5t 1
(c) F (s) = (g) F (s) = ln 1 + 2
(s + 0.1)(s2 + 0.01) s
1 1 1
(d) F (s) = (h) F (s) = −
s5 s2 s(es − 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
2s2 +5s+3 −10s
the Step Function block . The example of the function F (s) = 5s3 +2s2 +3s+1 e is shown in Figure
L14c.

Figure L14c: SIMULINK model for the Laplace transform inversion.

2s3 + 5s2 + 3s
To understand why the transfer function appearing in the Transfer function block is
5s3 + 2s2 + 3s + 1
2s2 + 5s + 3
and not recall that the Laplace transform of the Heaviside (step) function H(t − c)
5s3 + 2s2 + 3s + 1
e−cs
is H(s) = s . The model then outputs (on the Scope) the inverse transform of

2s3 + 5s2 + 3s e−cs 2s2 + 5s + 3


× = e−10s = F (s).
5s3 + 2s2 + 3s + 1 s 5s3 + 2s2 + 3s + 1
The output shown Figure L14d is obtained by double-clicking on the Scope (some of the parameters
such as the final 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.

F A factor of the form 1−e1−cs in F (s) indicates that the inverse transform f (t) is periodic with period
c. To determine the inverse transform numerically it suffices to remove this factor and determine the
inverse transform of the resulting function for 0 < t ≤ c. For example consider the function

1 1 − e−s 1 1 − e−s
F (s) = −s
= −s −s
= G(s) × with G(s) = .
s(1 + e ) s(1 + e )(1 − e ) 1 − e−2s 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
1

0.9

0.8

0.7

>> t=0:.1:2; 0.6

>> f=InvLaplace({[1]},{[1,0]},0,t) ... 0.5


-InvLaplace({[1]},{[1,0]},1,t);
0.4
>> plot(t,f)
0.3

0.2

0.1

0
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2

while using invlap yields


122 MATLAB sessions: Laboratory 14

1.2

function test
0.8
t=.1:.1:2;
f=invlap(@F,t,0); 0.6

plot(t,f)
%---------------- 0.4

function Fv = F(s) 0.2

Fv = (1-exp(-s))./s;
0

−0.2
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2

6. Comment on the differences 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


20(1 − e−πs ) 1
(a) F (s) = (b) F (s) =
s(s + 4s + 20)(1 + e−πs )
2 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
(n−1)
c1 y (n) + c2 y (n−1) + · · · + cn y 0 + cn+1 y = f (t) with y(0) = y0 , . . . , y (n−1) (0) = y0 given. (L14.6)

The solution of the IVP (L14.6) is the sum

y(t) = yh (t) + yf (t)

of the solutions of the homogeneous problem


(n) (n−1) (n−1) (n−1)
c1 yh + c2 yh + · · · + cn yh0 + cn+1 yh = 0 with yh (0) = y0 , . . . , yh (0) = y0 given, (L14.7)

and the forced problem with 0 initial conditions


(n) (n−1)
c1 yf + c2 yf + · · · + cn yf0 + cn+1 yf = f (t) with y(0) = 0, . . . , y (n−1) (0) = 0. (L14.8)

The Laplace transform of y is

P (s) F (s)
Y (s) = Yh (s) + Yf (s) = + (L14.9)
Q(s) Q(s)

with Q(s) = c1 sn + c2 sn−1 + · · · + cn s + cn+1 . The polynomial P (s) depends on the initial conditions
(n−1) (n−1)
y0 , . . . , y0 . If y0 = . . . = y0 = 0 then P (s) = 0. The function F (s) represents the Laplace
transform of f (t).

F 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 00 + 4y = sin t with y(0) = 1,
y 0 (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 Yh (s). The Laplace transform
of f (t) = sin t is F (s) = FF Q(s)
P (s)
where F P and F Q are given polynomials. Here F P (s) = 1 and
F (s) F P (s)
F Q(s) = s2 + 1. As a result the second fraction in (L14.9) can be written Q(s) = F Q(s)Q(s) . The
function cellprod then determines the product F Q(s)Q(s) as a single polynomial in the appropriate
format suitable for use in InvLaplace.

1.5
free response (forcing = 0)
response of forcing (IC = 0)
total response

0.5

−0.5

−1

−1.5
0 2 4 6 8 10 12 14 16 18 20

Figure L14e: Solution of the IVP y 00 +4y = sin t, y(0) = 1, y 0 (0) = 0 using InvLaplace with homogeneous
and forced contributions.

F If F (s) is unknown it must be computed numerically using NumLaplace. The inverse Laplace
F (s)
transform of Q(s) must then also be determined numerically using invlap. Because invlap requires for
F (s)
each value of t the evaluation of 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 inefficiency 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 0000 + 5y 00 + 4y = 0 with y(0) = 1, y 0 (0) = 0, y 00 (0) = −4, y 000 (0) = 1.


(b) y 00 + ay 0 + y = sin t with y(0) = 1, y 0 (0) = 0 for a = 5, 2, 1, 0.1.
½
sin t for t < π2
(c) y 00 + 4y = with y(0) = 1, y 0 (0) = 0.
1 for t ≥ 1
(d) y 00 + y =mod(floor(t),2) with y(0) = 1, y 0 (0) = 0.
MATLAB sessions: Laboratory 14 125

1.5

0.5

−0.5

−1 free response (forcing = 0)


response of forcing (IC = 0)
total response

−1.5
0 2 4 6 8 10 12 14 16 18 20

Figure L14f: Solution of the IVP y 00 + 4y = sin t, y(0) = 1, y 0 (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, Saff 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 (6th 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 specific ordering to the projects).

• Design Your Own Project


The basic idea is for each (team of) student(s) to find an application of differential 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, Saff & Snider. The differential 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 specific constants used in this lab do not pertain to any real situations. It’s not unreasonable
to ask the students to research this problem and identify specific 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 Office 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 first 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 modified (see next comment) so that it
is not unreasonable to solve without the use of linear algebra.
The application requires Kirchhoff’s voltage law, introduced in §3.5 (page 119) of Nagle, Saff 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 differential 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 fields.

• Hypergeometric Functions
A nice introduction to hypergeometric functions is presented in §8.8, page 484, of Nagle, Saff 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 differential 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 differential equations. To add emphasis
to this point, this project requires that you identify an application of differential equations in a subject
area of particular interest to you.
You are specifically 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 differential 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 clarifications from your mentor or differential 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 find 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 final 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 Keller’s theory of competitive running, published in 1973, track sprints of up to 300 meters
can be described by the differential equation

dv v
=A− .
dt τ
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 differential equation and how the terms combine
to form a complete model. What is an interpretation of the two parameters A and τ ? Does the
differential 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 differential 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 satisfied by d).

5. Find the acceleration a = a(t) function by differentiating v numerically (use the diff function).
Also, write a differential equation satisfied by a. What is the initial condition? Solve directly this
differential 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 runner’s maximum speed? How long does it take for the runner to reach 90% of this
maximum? Compare the final speeds in a 100 meter and a 200 meter race. Explain your findings.

8. Answer the previous two questions for general values of A and τ (graphically or algebraically).

Extending the Problem (Parameter Estimation)


Another aspect of differential equations is to use the solution to estimate the parameters of the problem.
This is a form of inverse problem, a sometimes difficult problem and active research area in applied
mathematics.
Race officials often record the split times of runners in addition to final 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 final 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 fit 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, let’s 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 modifications 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 first-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
1k 2 k
A −→ R −→ S

where k1 is the reaction rate for the conversion of A into R and k2 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 differential equations with appropriate initial conditions. For example
the equation describing changes in [R] reads

d[R]
= k1 [A] − k2 [R]
dt
(in the first reaction [A] disappears, and [R] appears, at a rate k1 [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) k1 = 1, k2 = 3,
(b) k1 = 3, k2 = 1,
(c) k1 = k2 = 2.
4. Use the ideas from first-order linear equations to find analytic solutions for [A], [R], and [S]. Be
sure to find solutions for all possible combinations of k1 and k2 (both positive).

Summary and Extensions


Use your findings to provide complete answers to the questions posed at the end of the first section for
any positive constants k1 and k2 . How is the model modified if one assumes that the first reaction is
1k
−→
now reversible in the form A ←− R? What if the reaction is second-order?
k3

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 finite 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 different 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 T
= s + rT 1 − − µT = f (T ).
dt Tmax

The parameters s, r, Tmax , 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 (Tmax) > 0 assure that the number of T-cells will stay
between 0 and Tmax . Under what constraints on the parameters are these conditions satisfied?

3. The fact that f is continuous and changes sign in the interval [0, Tmax ] implies, by the Intermediate
Value Theorem, that there is some value T ∗ for which f (T ∗ ) = 0. What is the significance of T ∗ ?
Determine T ∗ explicitly in terms of s, r, Tmax , and µ. Identify two parameters (functions of s, r,
Tmax , and µ) the ratio T ∗ /Tmax depends on.

Qualitative Analysis for a Specific Case


Realistic values of the parameters are s = 10, r = 0.03, Tmax = 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 Tmax . Do all solutions
stay in the desired interval?
134 Additional Project Descriptions

Qualitative Analysis for the General Case


T∗ µ s
We now investigate the behavior of as a function of α = and β = .
Tmax r rTmax
6. Select a grid of point in the (α, β) domain around the point corresponding to the specific 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, Scientific 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 difficult than in the previous project. Thinking about the biological interpretation of
each term should help you understand the model. The final 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 first, without necessarily investigating, the project “Normal T-cells”.

The Model
When attacked by the HIV virus T-cells are able to fight off the invasion for a period of time, but
eventually must give up to the onslaught. As a result, the immune system becomes less effective at
fighting 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
different populations: the size V of the HIV population, the number T of healthy T-cells, the number
TL of latently infected T-cells, and the number TA of actively infected T-cells. A different differential
equation is needed for each of T , TL , TA , and V . The complete model of four differential equations is
assembled by considering each population separately.

• Normal T-cells are produced and die according to processes identified 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 T + TL + TA
= s + rT 1 − − µT − k1 V T = fT (T, TL , TA , V ).
dt Tmax

• 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 differential equation
describing the rate of change of TL thus reads

dTL
= k1 V T − µTL − k2 TL = fTL (T, TL , TA , V ).
dt

• 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
dTA
= k2 TL − bTA = fTA (T, TL , TA , V ).
dt

• 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
= N bTA − k1 V T − aV = fV (T, TL , TA , V ).
dt
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 first ODE yields dTdt = s > 0, guaranteing that T > 0 for all t. Determine
conditions on the parameters guaranteing that none of TL , TA , 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, Tmax = 1700, µ = 0.02, b = 0.24, a = 2.4,
k1 = 2.4 × 10−5 , k2 = 3 × 10−3 , and N = 1400. What are reasonable initial conditions for T , TL ,
and TA ? 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 TL , TA , 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 first 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 patient’s 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 simplified 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, Scientific 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-differential 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 specific 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 = 41 Farad capacitor and a R = 6 Ohm resistor. A resistor with
unspecified 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.

C
L
r
©
©
H
H
©

H
H
E ©
©
R
Figure 1: 2-loop network
AA¢¢AA¢¢AA

The objectives are to determine steady-state currents (as functions of the resistance r), identify the
different 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 I1 (t) and I2 (t), respectively. First-order differential
equations for these currents can be obtained by applying Kirchhoff’s voltage law (§3.5 of the Nagle, Saff
& Snider text) to each loop of the network.

1. Write Kirchhoff’s law for each loop. Manipulate the equations until they have the form
· ¸ · ¸
dI1 /dt I
=A 1 +b
dI2 /dt I2
where A is a 2 × 2 matrix and b a 2-dimensional vector both depending on r. What are the initial
conditions?

1
2. How are the equations changed if the first loop contains also a 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 Imax = 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 difficult 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 14th 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 effort over the
years trying to bring some temporal order into this work. In [1] S. Rinaldi developed a relatively simple
differential 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 first 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 affection 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 £ ¡ ¢ ¤
= −α1 L + β1 P 1 − P 2 + AP ,
dt · ¸
dP AL
= −α2 P + β2 L + ,
dt 1+Z
dI
= −α3 I + β3 P.
dt
The parameters αi and βi , i = 1, 2, 3 are positive numbers. The quantities AP and AL describe the
physical appearance of Petrarch and Laura. Admittedly AP < 0 while AL >> 0.

1. The constants αi are called “forgetting” coefficients. Explain. What do you think about the
respective size of α1 and α2 ?

2. Explain in plain English the contribution of the different terms in the equations and their effect
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, AL = 2, AP = −1.

3. What are suitable initial conditions for P (0) and L(0)? Knowing that Petrarch wrote his first
poem about Laura years after they first 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
fixed)? Experiment with varying other parameters to obtain a similar behavior (hint: α’s must be
increased, β’s decreased, and physical appearances AP and AL 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 coefficients 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 one’s 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.), Petrarch’s Lyric Poems, Harvard University Press, 1976.
[3] Strogatz, S. H., Love affairs and differential equations, Math. Magazine 61 (1988) 35.
142 Additional Project Descriptions

P8. Hypergeometric Functions


The hypergeometric differential equation is the linear second-order ODE

x(1 − x)y 00 + (γ − (α + β + 1)x)y 0 − αβy = 0 (1)

with parameters α, β, and γ. For γ 6= 0, −1, −2, . . . the method of Frobenius yields a solution to this
equation as a power series
X∞
αβ (α)n (β)n n
y(x) = 1 + x+ x = F (α, β, γ; x) (2)
γ n=2
n!(γ)n

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 differen-
tial equations can be transformed into the hypergeometric differential equation. A number of properties
of hypergeometric functions were established in §8.8 of the Nagle/Saff/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 satisfied by F (α, β, γ; x)?
1
2. Prove the identity F (1, 1, 1; x) = 1−x . 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 x1 ,. . .,xm
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; 12 ) = 2,
(b) F ( 13 , 23 , 56 ; 32
27
) = 85 ,
(c) F ( 13 , 23 , 56 ; 32
27
) = 85 .

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 ( 12 , − 12 , 12 ; sin2 x) = cos x,
(b) F ( 12 , 12 , 32 ; x2 ) =
arcsin x
x ,
1 3 2 arctan x
(c) F ( 2 , 1, 2 ; −x ) = x ,
ln(1+x)
(d) F (1, 1, 2; −x) = x ,

Hypergeometric Functions and Differential Equations


d αβ
5. Prove that the identity F (α, β, γ; x) = F (α + 1, β + 1, γ + 1; x) holds for −1 < x < 1
dx γ
(a) analytically by differentiating the series (2) termwise.
d
(b) analytically by showing that F (α, β, γ; x) satisfies an appropriate differential equation with
dx
suitable initial conditions.
Rx
(c) numerically by comparing the direct evaluation of F (α, β, γ; x) via hypergeom.m with αβ γ 0
F (α+
1, β + 1, γ + 1; t) dt.
Additional Project Descriptions 143

6. Set α = β = 1 and γ = 12 . The hypergeometric


√ function F (1, 1, 12 ; x) then satisfies the ODE (1).
3 3 3
Show algebraically or numerically that xF ( 2 , 2 , 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?
1−(1−x)−m
8. Show the identity F (−m + 1, 1, 2; x) = 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 Differential Equations Using MATLAB,
Brooks/Cole Publishing Company, 1999. ISBN 0-534-35425-4
2. Paul Bugl, Explorations in Differential Equations Using MATLAB, companion manual to Differ-
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,
Differential Equations with MATLAB, John Wiley & Sons, Inc., 2000. ISBN 0-471-32227-X
4. Paul Davis, Differential 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. Saff & Arthur David Snider, Fundamentals of Differential Equations,
6/E, Addison-Wesley, 2004. ISBN: 0-321-14572-0
7. John C. Polking & David Arnold, Ordinary Differential 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 files described in this manual are available at
http://math.asu.edu/∼bdw/PUBLIC

General texts on MATLAB


1. Duane Hanselman and Bruce R. Littlefield, 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 Engineer’s 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 Scientific
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 Differential
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 fields of Mathematics and Science.

1. General Commands

Command Description Example


exit or quit terminate MATLAB session
help display m-file 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 infinity , 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, trigonometric functions sin(pi/3)-sec(x^2)
cot, sec, csc
acos, asin, atan, inverse trigonometric functions acos(0.6)
acot, asec, acsc
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-file function function gv=g(t)
gv=exp(-t)
@ m-file function handle feval(@g,3)
References 147

3. Array Creation and Manipulation

Command Description Example


[, ] array definition 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 x=1:2:9
index into array A(2:3,:)
rearrange 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 file save ’data.mat’ x A
load retrieve variables from file 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 find indices and values of nonzero elements i=find(x), [i,j]=find(A)
sum sum of array elements (along first 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 file 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 stopwatch timer tic
... [t,y]=ode45(@f,[0,20],1);
toc toc
input user input N = input(’How many? N = ’)
str = input(’Name ? = ’,’s’)
figure create/raise figure 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 semi-log scale plot semilogy(t,y,’r-’)
semilogy 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 2D/3D quiver (or velocity) plot quiver(X,Y,dX,dY)
quiver3
drawnow complete pending drawing drawnow
axis axis scaling axis equal, axis([0,1,0,2])
xlim set/get current x, y, z-axis limits xlim([0,2]), xlim
ylim
zlim
grid grid lines for plots grid on, grid off
legend add legend legend(’f(x)’,’g(x)’)
xlabel x, y, z-axis labels xlabel(’time t’)
ylabel
zlabel
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 file print -depsc out.eps

5. Logical Operations and Control Flow

Command Description Example


==, ∼=, <, <=, >, >= comparison if x>=2 & y∼=0
&, |, ∼ logical AND, OR, NOT z=sqrt(x-2)/y;
end
any, all test for any/all nonzeros any([0,1,2])
for ... repeat statements for i=2:10
... x(i)=x(i-1)+1;
end end
while ... indefinitely repeat statements while e<tol
... x(i)=x(i-1)+1; e=max(x);
end end
if ... conditionally execute statements if x==0
... y=1;
elseif ... elseif x==pi
... y=-1;
else else
... y=pi*sin(x)/(x*(x-pi));
end end
switch ... switch among cases switch x
case ... case 0
... y=1;
case ... case pi
... y=-1;
otherwise otherwise
... y=pi*sin(x)/(x*(x-pi));
end 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 Differential 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 find 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 IVP solver [t,y]=ode45(@f,[0,20],y0);
ode45 [t,y]=ode45(@f,[0,20],y0,[],param);
ode15s [t,y]=ode45(@f,[0,20],y0,options,param);
ode23s
ode23t
roots polynomial roots roots([1,4,3])
poly polynomial given roots poly([-1,-3])
characteristic polynomial 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 A\b

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