Professional Documents
Culture Documents
Fundamentals of Differential Equatins MATLAB Manual PDF
Fundamentals of Differential Equatins MATLAB Manual PDF
Bruno D. Welfert
to accompany
Fundamentals of
Differential Equations
Sixth Edition
and
Fundamentals of
Differential Equations
and
Boundary Value Problems
Fourth Edition
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
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
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.
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 >>.
ans =
ans =
1
2 Introduction to MATLAB
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
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.
F To obtain a description of the use of a particular function type help followed by the name of the
function. For example
F To get a list of other groups of MATLAB programs already available enter help:
>> help
HELP topics:
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 =
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
x =
Columns 1 through 4
Columns 5 through 8
Columns 9 through 12
6 Introduction to MATLAB
Columns 13 through 16
Columns 17 through 20
Column 21
2.0000
or simply
>> x=0:.1:2
x =
Columns 1 through 4
Columns 5 through 8
Columns 9 through 12
Columns 13 through 16
Columns 17 through 20
Column 21
2.0000
Try also
>> x=linspace(0,2,21)
x =
Columns 1 through 4
Columns 5 through 8
Columns 9 through 12
Columns 13 through 16
Columns 17 through 20
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
>> 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
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.
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
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
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 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
>> 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.
for <expression>
<list of commands>
end
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
function y=f(x)
if x==2
disp(’y is undefined at x = 2’)
else
y=1/(x-2);
end
Introduction to MATLAB 17
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
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 .
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).
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
Direction Fields
(§1.3, 5.4 of the Nagle/Saff/Snider text)
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
...
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
...
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
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
−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
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.
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
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
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.
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.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;
• understand how parameter dependent problems are implemented and the role of these parameters
in the solution 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.
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 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
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
10
−2
−4
−6
−8
−10
−10 −8 −6 −4 −2 0 2 4 6 8 10
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
(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:
For small enough h we get an approximation y1 for y(t1 ) by suppressing the . . ., namely
y1 = y0 + hf (t0 , y0 ). (L2.1)
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
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
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 :
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.
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)
Minor modifications are made to the function euler.m to implement the improved Euler method.
MATLAB sessions: Laboratory 2 47
impeuler.m
Note that the improved Euler approximation with 5 steps is already more accurate than the Euler
approximation with 50 steps! (hence the “improved”)
(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?
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
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).
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.
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):
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).
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.
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.
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.
−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 ,
...
n
X ∞ k
X
tk t
φn (t) = → = et (Taylor series of et ).
k! k!
k=0 k=0
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
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.
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.
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
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
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?
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))
s a - i b - r
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.
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.
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:
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.
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.
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
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?
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
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
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);
95
outside
first model
improved model
90
85
80
75
70
65
0 6 12 18 24 30 36 42 48
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.
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.
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
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
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
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
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.
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
`0 k
y
m
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
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
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
>> 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).
• Parameters can be continuously changed within a predefined range. To select which parameter
82 MATLAB sessions: Laboratory 8
to change select the appropriate item in the menu . Then use the slider
Finally the button resets parameter values to default values, while the button exits
the GUI.
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 θ
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
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
options = odeset(’Reltol’,1e-12,’AbsTol’,1e-12’);
[t,Y] = ode45(@f,[0,20],[theta0,v0],options,omega);
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
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.
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?
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
40
30
20
10
−10
−20
−30
−40
0 2 4 6 8 10 12 14 16 18 20
150
100
50
−50
−100
0 2 4 6 8 10 12 14 16 18 20
500
450
400
350
300
250
200
150
0 2 4 6 8 10 12 14 16 18 20
88 MATLAB sessions: Laboratory 9
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.
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 ];
>> 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
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)?
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.
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)
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
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
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
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
Figure L11c: Phase plot with eigenvector direction for the matrix A=[-1,6;-4,-6].
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
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.
y(t1 ) = y(t0 + h)
' y(t0 ) + hy 0 (t0 )
= y0 + hf (t0 , y(t0 ))
= y0 + hf (t0 , y0 ) ≡ y1 .
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
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?
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
(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.
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)
• 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)
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
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
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.
Figure L13d: The SIMULINK Library Browser Window: Windows (left), Unix (right)
Integrator Continuous
State-Space Continuous
Gain Math
Product Math
Sum Math
Scope Sinks
XY-Graph Sinks
Constant Source
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.
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 .
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
a single State-Space block to model the same problem. Your SIMULINK model should
look like
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
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.
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)
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
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
0.2
0.1
0
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
1.2
function test
0.8
t=.1:.1:2;
f=invlap(@F,t,0); 0.6
plot(t,f)
%---------------- 0.4
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?
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
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
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.
1.5
0.5
−0.5
−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
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
dv v
=A− .
dt τ
At the time of this analysis, the best constants were A = 12.2 m/s and τ = 0.892 s.
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?
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).
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
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
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”.
Bibliography
[1] Holland, C. D. and Anthony, R. G., Fundamentals of Chemical Reaction Engineering, Prentice-Hall
(1979).
Additional Project Descriptions 133
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.
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.
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
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
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
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?
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
C
L
r
©
©
H
H
©
r©
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.
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
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.
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
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
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 .
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
145
146 References
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
7. SIMULINK Blocks
Block Name Symbol Library
Integrator Continuous
State-Space Continuous
Fcn Functions
Gain Math
Product Math
Sum Math
Scope Sinks
XY-Graph Sinks
Constant Source