+ All Categories
Home > Documents > manualv2

manualv2

Date post: 26-Nov-2015
Category:
Upload: leo-kuts
View: 22 times
Download: 0 times
Share this document with a friend
Popular Tags:
155
MATLAB r Laboratory Manual with SIMULINK r examples Bruno D. Welfert to accompany Fundamentals of Differential Equations Sixth Edition and Fundamentals of Differential Equations and Boundary Value Problems Fourth Edition Nagle Saff Snider i
Transcript
Page 1: manualv2

MATLABr Laboratory Manual

with SIMULINKr examples

Bruno D. Welfert

to accompany

Fundamentals ofDifferential Equations

Sixth Edition

and

Fundamentals ofDifferential Equations

andBoundary Value Problems

Fourth Edition

Nagle Saff Snideri

Page 2: manualv2

MATLABr and SIMULINKr are registered trademarks of The MathWorks, Inc.MAPLEr is a registered trademark of Waterloo Maple, Inc.

c©2003 B. Welfert

ii

Page 3: manualv2

Contents

Preface v

1 Introduction to MATLAB 1The MATLAB Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Basics and Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Plotting with MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Scripts and Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10Matrices and Linear Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12MATLAB Programming and Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

2 Ordinary Differential Equationswith MATLAB 19Numerical Differentiation and Solution of the IVP . . . . . . . . . . . . . . . . . . . . . . . . . 19Direction Fields and Graphical Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20First-Order Scalar IVP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

Basic ode45 Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24Error Plot, Improving the Accuracy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29Parameter-Dependent ODE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

Higher-Order and Systems of IVPs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

3 MATLAB sessions 35Laboratory 1: First-Order Differential Equations, Graphical Analysis . . . . . . . . . . . . . . . 38

Direction fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38Additional Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

Laboratory 2: Numerical Solutions (Euler, Improved Euler) for Scalar Equations . . . . . . . . 42Euler’s Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42Improved Euler’s Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46Additional Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

Laboratory 3: Solution Sensitivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49Dependence of IVP Solution on IC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50Existence and Uniqueness . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52Additional Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54

Laboratory 4: Picard Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56Picard iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56Numerical Picard Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57Additional problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

Laboratory 5: Applications of First-Order Differential Equations . . . . . . . . . . . . . . . . . 61Population Growth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62Other Models, Parameter Estimation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

Laboratory 6: Further Applications of First-Order Differential Equations . . . . . . . . . . . . 66

iii

Page 4: manualv2

The Snowplow Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66Aircraft Guidance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67Heating and Cooling of Buildings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

Laboratory 7: Implementing Higher-Order Differential Equations . . . . . . . . . . . . . . . . . 72Reducing a Higher-Order ODE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72MATLAB Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72Additional Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

Laboratory 8: The Mass-Spring System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78Mass-Spring System without Damping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78Mass-Spring System with Damping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80The GUI spring.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81

Laboratory 9: The Pendulum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83The Undamped Case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83The Linearized Case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86With Damping Present . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86The Poe pendulum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88

Laboratory 10: Forced Equations and Resonance . . . . . . . . . . . . . . . . . . . . . . . . . . 89The Amplitude of Forced Oscillations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89Resonance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92Beats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92Additional Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93

Laboratory 11: Analytical and Graphical Analysis of Systems . . . . . . . . . . . . . . . . . . . 94An Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94Multiple Eigenvalue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97Complex Eigenvalues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99Additional Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101

Laboratory 12: Additional Numerical Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . 102Taylor and Runge-Kutta Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102Application to a System of ODEs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104Additional Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105

Laboratory 13: Introduction to SIMULINK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107An Example SIMULINK Model: spring1.mdl . . . . . . . . . . . . . . . . . . . . . . . . 107Building a Mass-Spring SIMULINK Model . . . . . . . . . . . . . . . . . . . . . . . . . . . 109Alternate SIMULINK Implementations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111

Laboratory 14: Laplace transform, application to linear IVPs . . . . . . . . . . . . . . . . . . . 114Laplace transform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114Inverse Laplace transform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116Applications to the solution of IVPs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122

4 Additional Project Descriptions 127Note to the Instructor: Group Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127P1. Design your Own Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129P2. The ODE of World-Class Sprint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130P3. Consecutive Reactions for Batch Reactors . . . . . . . . . . . . . . . . . . . . . . . . . . . 132P4. Normal T-Cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133P5. T-Cells in the Presence of HIV . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135P6. Design of an Electrical Network . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138P7. The Dynamics of Love . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140P8. Hypergeometric Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142

5 References 145Bibliography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145Appendix: MATLAB Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146

iv

Page 5: manualv2

Preface

This manual is designed to accompany the new edition of Fundamentals of Differential Equations (andBoundary 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 shouldhowever 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 areexpressed in familiar mathematical notation” (excerpt from The MathWorks website). MATLAB standsfor MATrix LABoratory and was originally written to provide easy access to matrix software developedby 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-productivityresearch, development, and analysis.” This manual explores the use of MATLAB in solving differentialequations and visualizing and interpreting their solutions. The main objectives are:

1. familiarize students with basic MATLAB programming to solve differential equations of varyingcomplexity,

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 laplaceand ilaplace in Laboratory 14. Custom functions which do not use this toolbox were used to illustratethe numerical evaluation of these transforms. An introduction to SIMULINK is given in Laboratory13. SIMULINK provides a tool for building and testing models using the power of MATLAB withoutrequiring 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 thecontent of this manual.

This manual includes two introductory chapters on MATLAB: the first one shows how to startMATLAB and how to use and organize basic commands. It explains in particular how to save groupsof commands in a file, which is important in creating programs that implement a whole problem. Thesecond chapter is more specific to differential equations. It goes over how to implement initial valueproblems and how to visualize the solution(s), using complete examples. Students are encouraged toread 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 generalnumerical implementation and execution issues when solving differential equations. This is done inthe context of specific applications, many of which are similar to the ones presented in the MAPLEcompanion manual. As noted there, these laboratory sessions vary in length and difficulty, and areincluded 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 kindsof 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

Page 6: manualv2

book by K. Pothoven. A project idea coming from an actual project carried out in a DifferentialEquations with MATLAB course I have been teaching is also included. Each project is briefly describedat the beginning of the chapter.

As always when using a computer software the user should be careful to respect the correct syntaxneeded for proper execution. In my experience this represents the most significant hurdle for studentswithout any background in computer programming. This manual is designed to help in this regard, byincluding simple examples and templates that students can conveniently use as a starting point for theirown applications. Ultimately, some effort must however be made by the student in order to assimilate theproper ways of using MATLAB by practicing with the examples included in this manual and adaptingthem to new problems.

The manuscript was prepared using the LATEX document preparation system. PostScript figureswere created using MATLAB or converted from screen capture in Jpeg format using jpeg2ps 1.9 byThomas Herz. The cover picture was created from the original book cover of the new (sixth) edition of theNagle, Saff and Snider text with a mask based on the MATLAB logo using PhotoShop. The MATLABgraphical user interfaces dfield6.m and pplane6.m by John Polking and David Arnold were briefly usedin this manual. A detailed description is available in their book Ordinary Differential Equations UsingMATLAB. Many of the MATLAB and SIMULINK programs used in this manual are available online athttp://math.asu.edu/∼bdw/PUBLIC. Partial funding for this work was provided by a grant to improveundergraduate education from the College of Liberal Arts and Sciences at Arizona State University.

Bruno WelfertArizona State UniversitySeptember 2003

vi

Page 7: manualv2

Chapter 1

Introduction to MATLAB

MATLAB is a computer software commonly used in both education and industry to solve a wide rangeof problems.

This chapter provides a brief introduction to MATLAB, and the tools and functions that help youto work with MATLAB variables and files.

The MATLAB Environment

F To start MATLAB double-click on the MATLAB shortcut icon or type matlab & at theprompt (Unix). The MATLAB desktop opens.

On the right side of the desktop you find the Command Window, where commands are entered atthe prompt >>.

On the left side you will generally find the Launch Pad and Workspace windows, and the CommandHistory and Current Directory windows. For all practical purposes we have in mind I recommend closingthe Launch Pad, Workspace, and Command History windows, if opened. It is convenient to keep theCurrent 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). Atypical MATLAB desktop is shown in Fig. 1.1.F To exit MATLAB do one of the following:

• Click on the close box at the top right of the MATLAB Desktop.

• Select File > Exit from the desktop File menu.

• Type quit or exit at the Command Window prompt >>.

Basics And Help

Commands are entered in the Command Window.F Basic operations are +, -, *, and /. The sequence

>> a=2; b=3; a+b, a*b,

ans =

5

ans =

1

Page 8: manualv2

2 Introduction to MATLAB

Figure 1.1: A typical MATLAB desktop

6

defines variables a and b and assigns values 2 and 3, respectively, then computes the sum a+b and productab. Each command ends with , (output is visible) or ; (output is suppressed). The last command on aline 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 =

1

verifies the trigonometric identity sin2 θ + cos2 θ = 1 for θ = π5 . A list of elementary math functions can

be obtained by typing help elfun in the Command window:

>> help elfun

Elementary math functions.

Page 9: manualv2

Introduction to MATLAB 3

Trigonometric.sin - Sine.sinh - Hyperbolic sine.asin - Inverse sine.asinh - Inverse hyperbolic sine.cos - Cosine.cosh - Hyperbolic cosine.acos - Inverse cosine.acosh - Inverse hyperbolic cosine.tan - Tangent.tanh - Hyperbolic tangent.atan - Inverse tangent.atan2 - Four quadrant inverse tangent.atanh - Inverse hyperbolic tangent.sec - Secant.sech - Hyperbolic secant.asec - Inverse secant.asech - Inverse hyperbolic secant.csc - Cosecant.csch - Hyperbolic cosecant.acsc - Inverse cosecant.acsch - Inverse hyperbolic cosecant.cot - Cotangent.coth - Hyperbolic cotangent.acot - Inverse cotangent.acoth - Inverse hyperbolic cotangent.

Exponential.exp - Exponential.log - Natural logarithm.log10 - Common (base 10) logarithm.log2 - Base 2 logarithm and dissect floating point number.pow2 - Base 2 power and scale floating point number.sqrt - Square root.nextpow2 - Next higher power of 2.

Complex.abs - Absolute value.angle - Phase angle.complex - Construct complex data from real and imaginary parts.conj - Complex conjugate.imag - Complex imaginary part.real - Complex real part.unwrap - Unwrap phase angle.isreal - True for real array.cplxpair - Sort numbers into complex conjugate pairs.

Rounding and remainder.fix - Round towards zero.floor - Round towards minus infinity.ceil - Round towards plus infinity.round - Round towards nearest integer.mod - Modulus (signed remainder after division).

Page 10: manualv2

4 Introduction to MATLAB

rem - Remainder after division.sign - Signum.

F To obtain a description of the use of a particular function type help followed by the name of thefunction. For example

>> help cosh

COSH Hyperbolic cosine.COSH(X) is the hyperbolic cosine of the elements of X.

F To get a list of other groups of MATLAB programs already available enter help:

>> help

HELP topics:

matlab\general - General purpose commands.matlab\ops - Operators and special characters.matlab\lang - Programming language constructs.matlab\elmat - Elementary matrices and matrix manipulation.matlab\elfun - Elementary math functions.matlab\specfun - Specialized math functions.matlab\matfun - Matrix functions - numerical linear algebra.matlab\datafun - Data analysis and Fourier transforms.matlab\audio - Audio support.matlab\polyfun - Interpolation and polynomials.matlab\funfun - Function functions and ODE solvers.matlab\sparfun - Sparse matrices.matlab\graph2d - Two dimensional graphs.matlab\graph3d - Three dimensional graphs.matlab\specgraph - Specialized graphs.matlab\graphics - Handle Graphics.matlab\uitools - Graphical user interface tools.matlab\strfun - Character strings.matlab\iofun - File input/output.matlab\timefun - Time and dates.matlab\datatypes - Data types and structures.matlab\verctrl - Version control.matlab\winfun - Windows Operating System Interface Files (DDE/ActiveX)matlab\demos - Examples and demonstrations.toolbox\local - Preferences.matlabR12\work - (No table of contents file)

For more help on directory/topic, type "help topic".

F Another way to obtain help is through the desktop Help menu, Help > MATLAB Help, or byconnecting to the Mathworks web site at www.mathworks.com.F MATLAB is case-sensitive. For example

>> theta=1e-3, Theta=2e-5; ratio=theta/Theta

theta =

Page 11: manualv2

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/0Warning: Divide by zero.

c =

Inf

with

>> d=0/0Warning: Divide by zero.

d =

NaN

Plotting with MATLAB

F To plot a function you have to create two arrays (vectors): one containing the abscissae, the other thecorresponding function values. Both arrays should have the same length. For example, consider plottingthe function

y = f(x) =x2 − sin(πx) + ex

x− 1for 0 ≤ x ≤ 2. First choose a sample of x values in this interval:

>> x=[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1, ...1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2]

x =

Columns 1 through 4

0 0.1000 0.2000 0.3000

Columns 5 through 8

0.4000 0.5000 0.6000 0.7000

Columns 9 through 12

Page 12: manualv2

6 Introduction to MATLAB

0.8000 0.9000 1.0000 1.1000

Columns 13 through 16

1.2000 1.3000 1.4000 1.5000

Columns 17 through 20

1.6000 1.7000 1.8000 1.9000

Column 21

2.0000

or simply

>> x=0:.1:2

x =

Columns 1 through 4

0 0.1000 0.2000 0.3000

Columns 5 through 8

0.4000 0.5000 0.6000 0.7000

Columns 9 through 12

0.8000 0.9000 1.0000 1.1000

Columns 13 through 16

1.2000 1.3000 1.4000 1.5000

Columns 17 through 20

1.6000 1.7000 1.8000 1.9000

Column 21

2.0000

Try also

>> x=linspace(0,2,21)

x =

Columns 1 through 4

0 0.1000 0.2000 0.3000

Page 13: manualv2

Introduction to MATLAB 7

Columns 5 through 8

0.4000 0.5000 0.6000 0.7000

Columns 9 through 12

0.8000 0.9000 1.0000 1.1000

Columns 13 through 16

1.2000 1.3000 1.4000 1.5000

Columns 17 through 20

1.6000 1.7000 1.8000 1.9000

Column 21

2.0000

F Note that an ellipsis ... was used to continue a command too long to fit in a single line.F The output for x can be suppressed (by adding ; at the end of the command) or condensed by enteringformat compact:

>> format compact>> x

Columns 1 through 40 0.1000 0.2000 0.3000

Columns 5 through 80.4000 0.5000 0.6000 0.7000

Columns 9 through 120.8000 0.9000 1.0000 1.1000

Columns 13 through 161.2000 1.3000 1.4000 1.5000

Columns 17 through 201.6000 1.7000 1.8000 1.9000

Column 212.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.2318Columns 13 through 1626.7395 20.5610 17.4156 15.4634

Columns 17 through 20

Page 14: manualv2

8 Introduction to MATLAB

14.1068 13.1042 12.3468 11.7832Column 2111.3891

Note that the function becomes infinite at x = 1 (vertical asymptote). The array y inherits the dimensionof x, namely 1 (row) by 21 (columns). Note also the use of parentheses.

IMPORTANT REMARKIn the above example *, / and ^ are preceded by a dot . in order for the expression to be evaluated foreach component (entry) of x. This is necessary to prevent MATLAB from interpreting these symbolsas standard linear algebra symbols operating on arrays. Because the standard + and - operations onarrays already work componentwise, a dot is not necessary for + and -.

The command

>> plot(x,y)

creates a Figure window and shows the function, see Fig. 1.2. The figure can be edited and manipulatedusing the Figure window menus and buttons. Alternately, properties of the figure can also be defineddirectly at the command line:

>> x=0:.01:2;>> y=(x.^2-sin(pi.*x)+exp(x))./(x-1);>> plot(x,y,’r-’,’LineWidth’,2);>> axis([0,2,-10,20]); grid on;>> title(’f(x)=(x^2-sin(\pi x)+e^x)/(x-1)’);>> xlabel(’x’); ylabel(’y’);

Page 15: manualv2

Introduction to MATLAB 9

Figure 1.2: A Figure window

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

−5

0

5

10

15

20

x

y

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

Figure 1.3: The function y = f(x) = x2−sin(πx)+ex

x−1 .

Page 16: manualv2

10 Introduction to MATLAB

The number of x-values has been increased for a smoother curve (what is the new size of x?). Thecurve now appears wider and in red. The range of x and y values has been reset (always a good ideain the presence of vertical asymptotes). A title and labels have been added. The resulting new plot isshown in Fig. 1.3. For more options type help plot in the Command Window.

Scripts and Functions

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

1. A script is simply a collection of MATLAB commands gathered in a single file. The value of thedata 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 specifiedany variable inside a function is local to the function and not available in the Workspace. Afunction invariably starts with the command

function output = function_name(input)

and should contain one or several commands defining the output.

Use a function when a group of commands needs to be evaluated multiple times.F To create a new script or function select the MATLAB desktop File menu File > New > M-file.In the MATLAB text editor window enter the commands as you would in the Command window. Tosave the file use the menu File > Save or File > Save As..., or the shortcut Save button .

Figure 1.4: The script myplot.m in the MATLAB Editor window.

F Examples of script/function:

1. script

myplot.m myplot.m (see Fig. 1.4).

Page 17: manualv2

Introduction to MATLAB 11

x=0:.01:2; % x-valuesy=(x.^2-sin(pi.*x)+exp(x))./(x-1); % y-valuesplot(x,y,’r-’,’LineWidth’,2); % plot in redaxis([0,2,-10,20]); grid on; % set range and add gridtitle(’f(x)=(x^2-sin(\pi x)+e^x)/(x-1)’); % add titlexlabel(’x’); ylabel(’y’); % add labels

2. script+function (two separate files)

myplot2.m (driver script)

x=0:.01:2; % x-valuesy=feval(@myfunction,x); % evaluate myfunction at xplot(x,y,’r-’,’LineWidth’,2); % plot in redaxis([0,2,-10,20]); grid on; % set range and add gridtitle(’f(x)=(x^2-sin(\pi x)+e^x)/(x-1)’); % add titlexlabel(’x’); ylabel(’y’); % add labels

myfunction.m (function)

function y=myfunction(x) % defines functiony=(x.^2-sin(pi.*x)+exp(x))./(x-1); % y-values

3. script+function (one single file)

myplot1.m (driver script converted to function + function)

function myplot1x=0:.01:2; % x-valuesy=feval(@myfunction,x); % evaluate myfunction at xplot(x,y,’r-’,’LineWidth’,2); % plot in redaxis([0,2,-10,20]); grid on; % set range and add gridtitle(’f(x)=(x^2-sin(\pi x)+e^x)/(x-1)’); % add titlexlabel(’x’); ylabel(’y’); % add labels%-----------------------------------------function y=myfunction(x) % defines functiony=(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 3when 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 anygiven 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 separatefile myfunction.m:

Page 18: manualv2

12 Introduction to MATLAB

>> x=2; y=myfunction(x)y =11.3891

A script can be called from another script or function (in which case it is local to that function).If any modification is made, the script or function can be re-executed by simply retyping the script

or function name in the Command Window (or use the up-arrow on the keyboard to browse throughpast commands).

IMPORTANT REMARKBy default MATLAB saves files in the Current Directory (folder). When entering MATLAB theCurrent Directory is the Work Directory (e.g., C:\matlabR12\work). Make sure the file is savedwhere you want it. To change directory use the Current Directory window or the Current Directorybox on top of the MATLAB desktop.

F A function file can contain a lot more than a simple evaluation of a function f(x) or f(t, y). But insimple cases f(x) or f(t, y) can simply be defined using the inline syntax. Compare

>> ...>> slope = feval(@f,2,1) % note use of @. Try also slope=f(2,1)slope =

3

where f.m is the file containing

function dydt = f(t,y)dydt = t^2-y;

to

>> ...>> f = inline(’t^2-y’,’t’,’y’)f =

Inline function:f(t,y) = t^2-y

>> slope = feval(f,2,1) % note no @slope =

3

However, an inline function is only available where it is used and not to other functions. It is notrecommended when the function implemented is too complicated or involves too many statements.

Matrices and Linear Algebra

We have used one-dimensional 1× 21 arrays x and y in previous examples. MATLAB can handle higherdimensional arrays. Two-dimensional arrays (matrices) are commonly used in many situations.F Matrices can be constructed in MATLAB in different ways. For example the 3 × 3 matrix A =

8 1 63 5 74 9 2

can be entered as

>> A=[8,1,6;3,5,7;4,9,2]A =

8 1 63 5 74 9 2

or

Page 19: manualv2

Introduction to MATLAB 13

>> A=[8,1,6;3,5,7;4,9,2]A =

8 1 63 5 74 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 63 5 74 9 2

or 3 columns

>> col1=[8;3;4]; col2=[1;5;9]; col3=[6;7;2]; A=[col1,col2,col2]A =

8 1 63 5 74 9 2

Note the use of , and ;. Concatenated rows/columns must have the same length. Larger matrices canbe created from smaller ones in the same way:

>> C=[A,A] % Same as C=[A A]C =

8 1 6 8 1 63 5 7 3 5 74 9 2 4 9 2

The matrix C has dimension 3 × 6 (“3 by 6”). On the other hand smaller matrices (submatrices) canbe extracted from any given matrix:

>> A(2,3) % coefficient of A in 2nd row, 3rd columnans =

7>> A(1,:) % 1st row of Aans =

8 1 6>> A(:,3) % 3rd column of Aans =

672

>> A([1,3],[2,3]) % keep coefficients in rows 1 & 3 and columns 2 & 3ans =

1 69 2

F Some matrices are already predefined in MATLAB:

>> I=eye(3) % the Identity matrixI =

1 0 00 1 0

Page 20: manualv2

14 Introduction to MATLAB

0 0 1>> magic(3)ans =

8 1 63 5 74 9 2

(what is magic about this matrix?)F Matrices can be manipulated very easily in MATLAB (unlike Maple). Here are sample commandsto exercise with:

>> A=magic(3);>> B=A’ % transpose of A, i.e, rows of B are columns of AB =

8 3 41 5 96 7 2

>> A+B % sum of A and Bans =

16 4 104 10 16

10 16 4>> A*B % standard linear algebra matrix multiplicationans =

101 71 5371 83 7153 71 101

>> A.*B % coefficientwise multiplicationans =

64 3 243 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 ofdifferentials equations:

1. x=A\b determines the solution x = A−1b of the linear system Ax = b. The array b must have asmany rows as the matrix A.

2. [S,D]=eig(A) determines the eigenvectors of A (columns of S) and associated eigenvalues (diagonalcoefficients of D) (note that the eig function has one input and two output arguments).

As an example consider the matrix A =magic(3) again and x =

123

:

>> A=magic(3)A =

8 1 63 5 74 9 2

>> x=[1,2,3]’ % same as x=[1;2;3]x =

123

Page 21: manualv2

Introduction to MATLAB 15

>> b=A*xb =

283428

>> A\b % this is x!ans =

123

>> inv(A)*b % less efficient and accurateans =

1.00002.00003.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 00 0 -4.8990

>> A*S(:,1)-D(1,1)*S(:,1) % test 1st eigenvector-eigenvalue pairans =1.0e-014 *

-0.17760.3553

-0.3553

Note the multiplicative factor 10−14 in the last computation. MATLAB performs all operations usingstandard IEEE double precision.

MATLAB Programming and Debugging

Several constructs are used in MATLAB:

1. repetitive loops (fixed number of times)

for <expression><list of commands>

end

2. repetitive loops (indefinite number of times)

while <expression><list of commands>

end

3. conditional branching

if expression

Page 22: manualv2

16 Introduction to MATLAB

<list of commands>elseif expression

<list of commands>:

else<list of commands>

end

or

switch expressioncase <expression>

<list of commands>:

case <expression><list of commands>

otherwise<list of commands>

end

The following examples illustrate the use of each construct:

1. for loop: determine the sum of the squares of integers from 1 to 10

S = 0; % initialize running sumfor k = 1:10

S = S+k^2;end

What is S? Verify with MATLAB.

2. while loop: determine the sum of the inverses of squares of integers from 1 until the inverse of theinteger square is less than 10−5

S = 0; % initialize running sumk = 1; % initialize current integerincr = 1; % initialize test valuewhile incr>=1e-10

S = S+incr;k = k+1;incr = 1/k^2;

end

What is the value of S returned by this script? Compare to∞∑

k=1

1k2

=π2

6.

Can k and incr be both initialized by 0?

3. if statement: evaluate y = 1x−2 for a given (but unknown) scalar x

function y=f(x)if x==2

disp(’y is undefined at x = 2’)else

y=1/(x-2);end

Page 23: manualv2

Introduction to MATLAB 17

or with switch statement:

function y=f(x)switch xcase 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 toimprove 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; Selapsed_time =

1.8830S =

1.6449

and

>> tic; S=sum(1./(1:1000000).^2); toc; Selapsed_time =

0.0800S =

1.6449

F Programming with MATLAB is fairly easy. Still a script or function may not execute properly dueto some programming error. In this case MATLAB returns an error indicating where it stopped andwhy. Most of the time this is sufficient to find out the error and correct it, especially when you get usedto 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 placeswithin 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. Thentry 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 pressreturn.

Exercises

Now that you have been through the essential elements of MATLAB relevant in this text, a good exerciseis to go through the commands and change values, functions, and problems to familiarize yourself withthe MATLAB syntax and commands introduced in this chapter.

Page 24: manualv2

18 Introduction to MATLAB

Page 25: manualv2

Chapter 2

Ordinary Differential Equationswith MATLAB

In this chapter we demonstrate the use of MATLAB in working with ordinary differential equations(ODE) and initial value problems (IVP) of the form

y′ = f(t, y),y(t0) = y0.

In particular, we discuss the following topics:

1. Numerical differentiation and solution of the IVP.

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

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

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

Numerical Differentiation and Solution of the IVP

Consider the linear ODE y′ = t2− y. To (numerically) verify that y(t) = t2− 2t +2 + Ce−t is a solutionfor any constant C for t ∈ [−3, 3] we pick C at random and compare both sides of the ODE with y = y(t)for a large number of t-values:

>> C=randn % random value using normal distributionC =

-1.4060>> h=.1; t=-3:h:3; % 61 values in [-3,3]. Same as t=linspace(-3,3,61)>> y=t.^2-2*t+2+C*exp(-t); % evaluate y(t)>> dy=diff(y); dt=diff(t); % difference between consecutive y’s and t’s>> rhs=t.^2-y; % evaluate rhs of ODE>> lhs=dy./dt; % evaluate lhs of ODE>> axis equal; axis([-4 4 -4 4]); grid on; % adjust look...>> plot(t(2:end),lhs,’r’,t,rhs,’b’) % plot lhs, rhs (adjust size of t for lhs)

Note that t is 1 × 61 while dy, dt, and lhs are 1 × 60 so that rhs must be plotted against t(2:end)(=t(2:61)) rather than t. Fig. 2.1 shows both lhs (' y′) and rhs (= f(t, y) = t2−y). Better accuracyis obtained for smaller h.

19

Page 26: manualv2

20 Ordinary Differential Equations with MATLAB

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

−3

−2

−1

0

1

2

3

4

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

Direction Fields(§1.3, 5.4 of the Nagle/Saff/Snider text)

>> t=-3:.5:3; y=-3:.5:3; % define grid of values in t and y directions>> [T,Y]=meshgrid(t,y); % creates 2d matrices>> dT=ones(size(T)); % dt=1 for all points>> dY=T.^2-Y; % dy=(t^2-y)*dt: this is the ODE>> quiver(T,Y,dT,dY) % draw arrows (t,y) --> (t+dt,y+dy)>> axis equal; axis([-4 4 -4 4]); grid on; % adjust look...>> print -depsc dfielda.eps % export plot (color encapsulated PostScript)

Longer arrows indicate larger values of y′. When y′ varies in a wide range a better perception of thedirection 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 forLaboratory 1 page 114.F Approximate verification that a given function is solution of a particular ODE can also be done bysimply superposing the function to the direction field. After the previous script add

>> hold ony=t.^2-2*t+2+C*exp(-t);plot(t,y,’r’,’LineWidth’,2);hold off

See Fig. 2.3.

Page 27: manualv2

Ordinary Differential Equations with MATLAB 21

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

−3

−2

−1

0

1

2

3

4

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

−3

−2

−1

0

1

2

3

4

Figure 2.2: Direction field for y′ = t2 − y (left: constant dt, right: scaled dt).

Page 28: manualv2

22 Ordinary Differential Equations with MATLAB

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

−3

−2

−1

0

1

2

3

4

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

F The Graphical User Interface dfield6 from J. Polking (available at http://math.rice.edu/∼dfield)can also be used to plot the direction field and selected solution curves. ODEs with up to two parameterscan be entered in a setup window, see Figure 2.4. A sample display window is shown in Figure 2.5.

Page 29: manualv2

Ordinary Differential Equations with MATLAB 23

Figure 2.4: The dfield6 setup GUI

Figure 2.5: The dfield6 direction field plot

Page 30: manualv2

24 Ordinary Differential Equations with MATLAB

First-Order Scalar IVP(§3.6, 5.3 of the Nagle/Saff/Snider text)

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

(2.1)

The exact solution is y(t) = t− 1 + 2e−t. A numerical solution can be obtained using various MATLABsolvers. The standard MATLAB ODE solver is ode45. Help on ode45 can be obtained by typing

>> help ode45ODE45 Solve non-stiff differential equations, medium order method.

[T,Y] = ODE45(ODEFUN,TSPAN,Y0) with TSPAN = [T0 TFINAL] integrates thesystem of differential equations y’ = f(t,y) from time T0 to TFINAL withinitial conditions Y0. Function ODEFUN(T,Y) must return a column vectorcorresponding to f(t,y). Each row in the solution array Y corresponds toa time returned in the column vector T. To obtain solutions at specifictimes T0,T1,...,TFINAL (all increasing or all decreasing), useTSPAN = [T0 T1 ... TFINAL].

[T,Y] = ODE45(ODEFUN,TSPAN,Y0,OPTIONS) solves as above with defaultintegration properties replaced by values in OPTIONS, an argument createdwith the ODESET function. See ODESET for details. Commonly used optionsare scalar relative error tolerance ’RelTol’ (1e-3 by default) and vectorof absolute error tolerances ’AbsTol’ (all components 1e-6 by default).

[T,Y] = ODE45(ODEFUN,TSPAN,Y0,OPTIONS,P1,P2...) passes the additionalparameters P1,P2,... to the ODE function as ODEFUN(T,Y,P1,P2...), and toall functions specified in OPTIONS. Use OPTIONS = [] as a place holder ifno options are set.

...

Example[t,y]=ode45(@vdp1,[0 20],[2 0]);plot(t,y(:,1));

solves the system y’ = vdp1(t,y), using the default relative errortolerance 1e-3 and the default absolute tolerance of 1e-6 for eachcomponent, and plots the first component of the solution.

See alsoother ODE solvers: ODE23, ODE113, ODE15S, ODE23S, ODE23T, ODE23TBoptions handling: ODESET, ODEGEToutput functions: ODEPLOT, ODEPHAS2, ODEPHAS3, ODEPRINTODE examples: RIGIDODE, BALLODE, ORBITODE

...

Comments on advanced features have been omitted.

Basic ode45 Usage

The basic usage of ode45 requires a function ODEFUN, a time interval on which to solve the IVP, andan initial condition. For scalar first-order ODEs the function may often be specified using the inlineMATLAB command. A complete MATLAB solution would read:

Page 31: manualv2

Ordinary Differential Equations with MATLAB 25

1 f = inline(’t-y’,’t’,’y’);2 [t,y] = ode45(f,[0,3],1);3 plot(t,y)

(line numbers are not part of the commands!) Line 1 defines the function f as a function of t and y, i.e.,f(t, y) = t − y. This is the right-hand side of the ODE (2.1). Line 2 solves the IVP numerically usingthe ode45 solver. The first argument is the function f, the second one determines the time interval onwhich to solve the IVP in the form [initial time, final time], and the last one specifies the initial valueof y. The output of ode45 consists of two arrays: an array t of discrete times at which the solution hasbeen approximated, and an array y with the corresponding values of y. These values can be listed inthe Command Window as

[t,y]ans =

0 1.00000.0502 0.95220.1005 0.90930.1507 0.87090.2010 0.83690.2760 0.79360.3510 0.75900.4260 0.73220.5010 0.71290.5760 0.70030.6510 0.69400.7260 0.69370.8010 0.69880.8760 0.70890.9510 0.72371.0260 0.74291.1010 0.76611.1760 0.79301.2510 0.82341.3260 0.85711.4010 0.89371.4760 0.93311.5510 0.97501.6260 1.01941.7010 1.06601.7760 1.11461.8510 1.16511.9260 1.21742.0010 1.27142.0760 1.32682.1510 1.38372.2260 1.44192.3010 1.50132.3760 1.56182.4510 1.62342.5260 1.68592.6010 1.74942.6760 1.81362.7510 1.87872.8260 1.94452.9010 2.0109

Page 32: manualv2

26 Ordinary Differential Equations with MATLAB

2.9257 2.03302.9505 2.05512.9752 2.07733.0000 2.0996

For example the approximate solution at t ' 1.0260 is y ' 0.7429. Unless specific values of y are neededit is better in practice to simply plot the solution to get a sense of the behavior of the solution. Line3 thus plots y as a function of t in a figure window. The plot, shown in Figure 2.6, can be saved orexported in various formats using the File menu of the figure window.

0 0.5 1 1.5 2 2.5 30.6

0.8

1

1.2

1.4

1.6

1.8

2

2.2

Figure 2.6: Solution of (2.1).

Error Plot, Improving the Accuracy

Error plots are commonly used to estimate the accuracy in the numerical solution. Here the error isthe difference between the exact solution y(t) = t− 1 + 2e−t and the numerical approximation obtainedfrom ode45. Since this approximation is only given at specified time values (contained in the array t)we only evaluate this error at these values of t:

err = t-1+2*exp(-t)-yerr =1.0e-005 *

00.02780.04070.0162

-0.00420.17720.26380.0989

-0.04310.0942

Page 33: manualv2

Ordinary Differential Equations with MATLAB 27

0.16100.0414

-0.06150.04230.09380.0070

-0.06750.01100.0506

-0.0123-0.0663-0.00690.0235

-0.0221-0.0611-0.01630.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 isbest to use a logarithmic scale in the direction corresponding to err in the plot. To avoid problems withnegative numbers we plot the absolute value of the error (values equal to 0, e.g. at the initial time, arenot 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 defaultaccuracy ode45 uses to determine the approximation. To do this use the MATLAB odeset commandprior 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.

Page 34: manualv2

28 Ordinary Differential Equations with MATLAB

0 0.5 1 1.5 2 2.5 310

−8

10−7

10−6

10−5

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

0 0.5 1 1.5 2 2.5 310

−16

10−15

10−14

10−13

10−12

10−11

10−10

Figure 2.8: Error in the solution of (2.1) computed by ode45 with a better accuracy.

Page 35: manualv2

Ordinary Differential Equations with MATLAB 29

Integration

For initial value problems of the form

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

the solution can be explicitly obtained as

y(t) = y0 +∫ t

t0

f(u)du. (2.3)

To obtain a numerical approximation of y at some t 6= t0 one can use ode45 and solve the IVP, or usean integration routine such as quadl. For f(t) = sin t and y(0) = −1, the value y(π) is computed asfollows.

>> f = inline(’sin(t)’,’t’); % one variable>> tf = pi/2; format long;>> yf = -1+quadl(f,0,tf) % formula (2.3)yf =

0.99999997747113>> f = inline(’sin(t)’,’t’,’y’); % two variables>> [t,y] = ode45(f,[0,tf],-1);>> yf = y(end) % computed by solving (2.2)yf =

0.99999999832175

The exact answer is of course yf = 1. Note that quadl requires a function of one variable while ode45requires a function of two variables (even if y does not explicitly appear in the right-hand side of theODE). The accuracy of the approximation can also be increased in quadl, type help quadl for moreinformation.

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 ofode45 (as below) or saved in a separate m-file (see page 10). Consider for example the IVP

y′ = −a (y − e−t)− e−t,y(0) = 1.

(2.4)

with exact solution y(t) = e−t (independent of the parameter a!). An implementation of the MATLABsolution follows.

1 function ex_with_param2 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 line4 the parameter is passed to ode45 as the 5th argument (the 4th argument is reserved for setting optionssuch as the accuracy using odeset, see page 27, and the placeholder [] must be used if default options

Page 36: manualv2

30 Ordinary Differential Equations with MATLAB

are used). Correspondingly the function f defined lines 8-9 must include a 3rd argument correspondingto 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 simplyentering y(end).

The m-file ex with param.m is executed by entering ex with param at the MATLAB prompt. Theoutput is

>> ex_with_paramy(3) = 0.049787length of y = 45

F The additional line 6 in the file lists the length of the array y computed by ode45. It is interestingto check the size of y obtained for larger values of a. For example for a = 1000 we obtain

>> ex_with_paramy(3) = 0.049792length of y = 3621

This means that ode45 needed to take smaller step sizes to cover the same time interval compared tothe 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 solutionsapproach the solution of (2.4), see Figure 2.9.

0 0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.1

0.9

0.91

0.92

0.93

0.94

0.95

0.96

0.97

0.98

0.99

1

t

y

y ’ = − a (y − exp( − t)) − exp( − t) a = 1

0 0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.1

0.9

0.91

0.92

0.93

0.94

0.95

0.96

0.97

0.98

0.99

1

t

y

y ’ = − a (y − exp( − t)) − exp( − t) a = 1000

Figure 2.9: Direction field and sample solutions in the t-y window [0, 0.1] × [0.9, 1] as obtained usingDFIELD6: a = 1 (left) and a = 1000 (right).

F Other MATLAB ODE solvers are designed to better handle stiff problems. For example replace ode45with 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_paramy(3) = 0.049787length of y = 18

Page 37: manualv2

Ordinary Differential Equations with MATLAB 31

Higher-Order and Systems of IVPs(§5.2, 5.4, 5.5 of the Nagle/Saff/Snider text)

We show here how to extend the use of ode45 to systems of first-order ODEs (the same holds for othersolvers such as ode15s). Higher-order ODEs can first be transformed into a system of first-order ODEsto 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 populationsu1 = u1(t) and u2 = u2(t):

du1

dt= au1 − bu1u2,

du2

dt= −cu2 + du1u2

(2.5)

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 11page 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 isvery similar to the case of a single ODE, except that vectors must now be used to describe the unknownfunctions.

1 function ex_with_2eqs2 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 parametersare passed to the ODE solver ode45 as extra arguments (starting from the 5th), as many as there areparameters in the problem (4 here). The output array y of ode45 now has 2 columns, corresponding toapproximations for u1 and u2, respectively, instead of a single one. In line 5 these quantities are thereforeretrieved and stored in arrays u1 and u2, which are descriptive names. The part of the program definingthe ODE system includes lines 11-13. Note that all the parameters appearing as arguments of ode45must 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 thedefinition 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 firstcoefficient is the first right-hand side (du1

dt ) and the second coefficient the second right-hand side (du2dt ).

F Lines 6-10 correspond to the visualization of the results in a single figure. The subplot commandis used somewhat creatively here. The plot includes the time series of u1 and u2, and a phase plotrepresenting the evolution of u2 in terms of u1. Because the scales of u1 and u2 are different it is bestusing two different graphs for u1 and u2 here. Note that u1 and u2 vary cyclically. The periodic evolutionof the two populations becomes clear from the closed curve u2 vs. u1 in the phase plot.

Page 38: manualv2

32 Ordinary Differential Equations with MATLAB

0 5 10 1540

60

80

100

120

140

u1

u 2

0 2 4 6 8 10 12 14 16 18 200

5

10

15

u 1

0 2 4 6 8 10 12 14 16 18 200

50

100

150

u 2

Figure 2.10: Lotka-Volterra example.

F The following diagram explains the logic behind the selection of the arguments of the subplotcommand in the program ex with 2eqs.

subplot(4,1,1)

subplot(4,1,2)

subplot(2,1,2)

u1 vs. t

u2 vs. t

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

du1=−cu2 + du1u2

au1 − bu1u2= f(u1, u2). (2.6)

Page 39: manualv2

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

0 5 10 15

40

50

60

70

80

90

100

110

120

130

140

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

F The Graphical User Interface PPLANE6 from J. Polking (available at http://math.rice.edu/∼dfield)can also be used to get an idea of what phase plots can be expected to look like, see Figure 2.12. Asample display window is shown in Figure 2.13.

ODESOLVE GUI

We briefly mention the MATLAB Graphical User Interface odesolve.m by J. C. Polking, Rice University.This GUI allows the user to solve arbitrary systems of ODEs. However it requires the MATLAB SymbolicToolbox, which is not widely available on campuses. To some extent it also defeats the purpose oflearning some MATLAB programming. In this manual we preferred instead introducing the reader tothe SIMULINK package, which is a more helpful tool in the design of models and is extensively used inindustry. Laboratory 13 page 107 is dedicated to this package.

Page 40: manualv2

34 Ordinary Differential Equations with MATLAB

Figure 2.12: The PPLANE6 setup GUI

Figure 2.13: The PPLANE6 phase plot with a sample solution curve

Page 41: manualv2

Chapter 3

MATLAB sessions

In the previous chapters we gave a general introduction to MATLAB and an introduction on usingMATLAB to solve differential equations. In this chapter, we present 13 laboratory sessions for use inan introductory class on differential equations. The idea behind these labs is to coordinate the use ofMATLAB with class instruction in differential equations.

The MATLAB sessions deal with many of the most important numerical aspects of solving differentialequations as well as building and understanding ODE models. Many of the labs are connected with thematerial presented in the text Fundamentals of Differential Equations by Nagle, Saff and Snider andother 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 ofhow differential equations are solved numerically. Using MATLAB presents several advantages. Thestudent will

• easily visualize the behavior of solutions by means of direction fields and phase planes;

• be able to handle mathematically intractable problems and generate numerical solutions;

• understand how parameter dependent problems are implemented and the role of these parametersin the solution of differential equations;

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

• solve different types of problems from various fields of Science and Engineering.

The computer laboratory exercises that follow each session (or each section in a session) require thestudents 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 includesproblems for them to do. These problems range from simple problems, where the student must simplyfill-in dots ... left in a MATLAB code, to more involved problems that require working out a completeMATLAB code. Additionally, the students are asked to summarize the observations and conclusionsthey obtained while doing the exercises.

The laboratories should be used with discretion depending on the class situation. Some laboratoriesdeal more with numerical or graphical techniques, others focus more on applications. There is muchmore material here than can be used during a single semester course. Instructors may wish to use onlyparts of some laboratories. Some laboratories are lengthier than others and some parts may need to beomitted.

What follows is a brief synopsis of each laboratory session.

• Laboratory 1: First-Order Differential Equations, Graphical Analysis Using DirectionFields(§1.3 in Nagle/Saff/Snider text)

In this laboratory the students are shown how to plot direction fields for first-order differential

35

Page 42: manualv2

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

• 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 foreach 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 solutionsand how numerical techniques and solvers available in MATLAB handle these problems. Studentsare also shown how to recognize pure integration and autonomous problems from the directionfield, 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 interms of exact calculations. The technique, which is perhaps more appropriately illustrated usinga symbolic manipulator (e.g., the MATLAB Symbolic Toolbox) can also be implemented at anumerical level. An explanation of how this can be done is given in the lab. A number of exercisesis included for the students to exercise with the two implementations proposed in the laboratoryand 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 tomodel real world phenomena by means of differential equations. First, three standard models arediscussed for population growth - the exponential, logistic, and modified logistic (also known asNagumo) models. Direction fields are generated to study the behavior of solutions to differentialequations modelling the growth. Other phenomena such as cooling modelled by Newton’s law ofcooling, 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 threeapplications: 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 theNagle, 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 istaught first how to reduce higher-order ODEs to sets of first-order differential equations and writethe result in system form, then how to use built-in MATLAB commands to indiscriminately solvenumerically both homogeneous and non-homogeneous problems. Euler’s method is also applied tothe 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, thenwith damping. The model is explained in terms of mechanical forces. Students are shown theeffect of damping on the long time behavior of the solution. A Graphical User Interface modelling

Page 43: manualv2

MATLAB sessions 37

the actual movement of the system is used to establish a better connection between the graphicalrepresentation of the solution and the physical state of the system.

• Laboratory 9: The Pendulum(§4.7 of the Nagle/Saff/Snider text)

This is another application of second-order differential equations. The motion of a simple pendulumis modelled by a nonlinear ODE. The origin of the ODE is clearly explained in terms to mechanicalforces. A comparison between the full nonlinear model on one hand, and a linearized model on theother hand, establishes the limits of the linearized model. The effect of damping is also investigated.The ideas of energy conservation and dissipation are introduced in the form of exercises.

• Laboratory 10: Forced Equations and Resonance(§4.9 of the Nagle/Saff/Snider text)

In this laboratory we take a deeper look at second-order, non-homogeneous equations. We concen-trate on equations that have a periodic forcing term, such as a mass-spring system under periodicstimulus. We first analyze the amplitude of the resulting oscillation that develops after a certaintime, and show how, in cases of low damping/friction, this amplitude may dramatically increasewhen the forcing term and the free system come into resonance. The phenomenon of beats is alsoexplained.

• Laboratory 11: Analytical and Graphical Analysis of Systems(§5.1, 5.2, 5.4 and §9.1-9.6 of the Nagle/Saff/Snider text)

The focus in this laboratory is on two-dimensional linear systems. Students are shown how to de-termine eigenvalues and eigenvectors of a matrix, and how to use the information to determine thesolution of a linear homogeneous ODE system. Phase plots for various cases (distinct real eigen-values, equal real eigenvalues, distinct complex conjugate eigenvalues) help in the understandingof the behavior of solutions.

• Laboratory 12: Additional Numerical Techniques and Stability(§3.6, 3.7 and §5.3 of the Nagle/Saff/Snider text)

In this laboratory the notion of order of a numerical method is introduced and illustrated withnumerical techniques somewhat more sophisticated than Euler’s method, such as the Taylor methodof order 2 and the Runge-Kutta of order 4. Students are shown how to apply these methods toscalar equations as well as systems. Examples and problems used in this laboratory focus oncelestial mechanics.

• Laboratory 13: Introduction to SIMULINKThis laboratory is a wide departure from the other laboratory sessions in the sense that no MAT-LAB command is needed. Instead students are shown how to assemble a SIMULINK GUI modelassociated to a given system of differential equations and use it to simulate the solution of themodel.

• Laboratory 14: Laplace transformThis session considers numerical implementations of the Laplace and inverse Laplace transformsas well as symbolic functions used to obtain these transforms (if the MATLAB Symbolic Toolboxis available). Applications to solving linear initial value problems are included. One goal of thislab is to make students aware of the difficulty in evaluating the transform nume2ically.

Page 44: manualv2

38 MATLAB sessions: Laboratory 1

Laboratory 1First-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 viewpointand make use of direction fields. Our goal is to learn how to

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

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

Direction fields

A direction field for a scalar first-order differential equation is a two-dimensional t-y plot of arrows (orline 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 thatthe arrow is tangent to the solution curve passing through the point (t, y). The direction field providesa simple way to “visualize” solutions without actually solving the ODE.

Consider the ODEdy

dt= y′ = 1− sin y. (L1.1)

We use the script page 20 to create a function file dirfield.m. The inputs of the function dirfieldare 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 normalizeS = feval(f,T,Y);N = sqrt(1+S.^2);dT = 1./N; dY = S./N;switch typecase ’arrow’; quiver(T,Y,dT,dY);case ’line’; quiver(T,Y,dT,dY,’.’);otherwise; disp(’type not implemented’);endaxis 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.mwindow = [-10,10,-10,10];dirfield(@f,window,’arrow’);

Page 45: manualv2

MATLAB sessions: Laboratory 1 39

title(’Direction field of y’’=1-sin y’); % note the use of ’’%------------------------------------------------------------function dydt = f(t,y)% defines right-hand side of ODEdydt = 1-sin(y);

It is important here that f be defined in Lab1a.m so as to accept matrix arguments. Make sure bothfiles dirfield.m and Lab1a.m are saved in the current directory.

Try help dirfield and help Lab1a. What does MATLAB return? Type Lab1a in the CommandWindow to get Fig. L1a.

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

−8

−6

−4

−2

0

2

4

6

8

10

Direction field of y’=1−sin y

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

1. Answer the following questions regarding what you see in Fig L1a.

(a) If a solution has initial value y(0) = 4 what will be its behavior as t gets larger? as t getssmaller? 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 fromconsidering the ODE (L1.1)? Explain.

(c) If a solution has initial value y(0) = 4− 2π, what would the general shape of the solution becompared to the case y(0) = 4? How can you justify this using the ODE?

(d) What are equilibrium (constant) solutions?

Page 46: manualv2

40 MATLAB sessions: Laboratory 1

(e) Use the GUI dfield6.m to check the shape of the direction field shown in Fig. L1a and drawsome of the solutions (by clicking within the direction field window obtained) to confirm yourobservations. Fig. L1b shows what you should obtain.

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

2. Consider the differential equation

dy

dt= y′ = y(y + 1)(y − 2). (L1.2)

(a) Examine the direction field in the window 0 ≤ t ≤ 5, −2 ≤ y ≤ 4 using dirfield.m. Whatis the limit of y(t) as t →∞ if y(0) = 1.9? If y(0) = 2.1?

(b) Use the GUI dfield6.m to draw various representative solutions. Do any of the solutioncurves ever cross each other? Do you know why? (see Theorem 1 in §1.2 of the text by Nagle,Saff, and Snider.)

(c) If y(0) = 12 can y eventually be −1? Why?

3. Use dirfield.m AND dfield6.m to plot the direction field and some solution curves for each ofthe following differential equations in the window −5 ≤ t ≤ 5, −5 ≤ y ≤ 5. In each case determinewhether there exist any equilibrium solutions and characterize the appearance of the solutions.

Page 47: manualv2

MATLAB sessions: Laboratory 1 41

(a) y′ = sin t.

(b) y′ = sin y.

(c) y′ = sin t sin y.

Additional Problems

4. For each of the following ODEs plot the direction field using the method of your choice (dirfield.mor DFIELD6) and answer the following questions:

(a) What is the behavior of solutions as t approaches ∞?

(b) Do small variations in initial conditions lead to large changes in the solutions as t increases?

(c) Are solution periodic? If so, what is the period?

(d) Do solutions tend to an asymptote? If so, what is that asymptote?

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

2

5. For what values of t or y is the ODE y′ = − ty defined? Illustrate and discuss the behavior of

solutions.

6. Show that a solution y = y(t) of y′ = f(t, y) is even if f is an odd function of t (i.e., f(−t, y) =−f(t, y)). Use this to find a few ODEs whose solutions are symmetric with respect to the y-axis.Verify by plotting the direction field.

Page 48: manualv2

42 MATLAB sessions: Laboratory 2

Laboratory 2Numerical 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 numericalapproximations. Our objective is as follows.

1. Implement Euler’s method as well as an improved version to numerically solve an IVP.

2. Compare the accuracy and efficiency of the methods with methods readily available in MATLAB.

3. Apply the methods to specific problems and investigate potential pitfalls of the methods.

Euler’s Method

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

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

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

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

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

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

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

y(t1) = y(t0) +∫ t1

t0

f(s, y(s))ds. (L2.2)

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

yn+1 = yn + hf(tn, yn)tn+1 = tn + h

Geometrically, the approximation made is equivalent to replacing thesolution curve by the tangent line at (t0, y0). From the figure we have

f(t0, y0) = f(t0, y(t0)) = y′(t0) = tan θ =y1 − y0

h,

from which (L2.1) follows.

.........

..............................

s

s

y0

y1

y(t1)

t0 t1

θ

h

¡¡

¡¡

¡¡

As an example consider the IVP

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

Note that here f does not explicitly depend on t (the ODE is called autonomous), but does implicitlythrough 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 thesenames in case they have been used already in the same MATLAB work session.

Page 49: manualv2

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 approximationsat 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.6000t =

0 0.1000>> y(3)=y(2)+h*f(t(2),y(2)), t(3)=t(2)+h,y =

3.0000 3.6000 4.3200t =

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.1840t =

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 43.0000 3.6000 4.3200 5.1840Column 56.2208

t =Columns 1 through 4

0 0.1000 0.2000 0.3000Column 50.4000

>> y(6)=y(5)+h*f(t(5),y(5)), t(6)=t(5)+h,y =

Columns 1 through 43.0000 3.6000 4.3200 5.1840Columns 5 through 66.2208 7.4650

t =Columns 1 through 4

0 0.1000 0.2000 0.3000Columns 5 through 60.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 commandcan 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:

Page 50: manualv2

44 MATLAB sessions: Laboratory 2

>> [t(:),y(:)] % same as [t’,y’] hereans =

0 3.00000.1000 3.60000.2000 4.32000.3000 5.18400.4000 6.22080.5000 7.4650

A better way is to plot y vs t:

>> plot(t,y); axis tight;

0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.53

3.5

4

4.5

5

5.5

6

6.5

7

7.5

0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.53

3.5

4

4.5

5

5.5

6

6.5

7

7.5

8

Figure L2a: Euler’s method applied to y′ = 2y, y(0) = 3 with step h = 0.1 (left) and h = 0.550 = 0.01

(right).

See Fig. L2a, left. If more steps are required it is more convenient to use a do loop. The followingfunction implements these ideas.euler.m

function [tout,yout] = euler(f,tspan,y0,N)% solves the IVP y’=f(t,y), y(tspan(1))=y0 up to t=tspan(2)% using Euler’s method with N time steps% use: euler(f,[tmin,tmax],y0,N) (or @f)h = (tspan(2)-tspan(1))/N;t = tspan(1); tout = t;y = y0(:); yout = y.’;for n=1:N

y = y+h*feval(f,t,y); t = t+h;yout = [yout; y.’]; tout = [tout; t];

end

>> [t,y] = euler(f,[0,.5],3,50); % use @f if defined in separate function>> [t,y]ans =

0 3.00000.0100 3.06000.0200 3.12120.0300 3.18360.0400 3.2473

Page 51: manualv2

MATLAB sessions: Laboratory 2 45

0.0500 3.3122: :

0.4500 7.31360.4600 7.45980.4700 7.60900.4800 7.76120.4900 7.91640.5000 8.0748

An even longer output is obtained for larger values of N . Obviously, graphing the approximate solutionusing 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 thetwo approximations we plot both approximations on the same figure, together with the exact solutiony(t) = 3e2t:

>> [t5,y5] = euler(f,[0,.5],3,5); % use @f if defined in separate function>> [t50,y50] = euler(f,[0,.5],3,50);>> t = linspace(0,.5,100); y = 3*exp(2*t);>> plot(t5,y5,’ro-’,t50,y50,’bx-’,t,y,’k-’); axis tight;>> legend(’Euler N = 5’,’Euler N = 50’,’Exact’,2);

0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.53

3.5

4

4.5

5

5.5

6

6.5

7

7.5

8 Euler N = 5Euler N = 50Exact

Figure L2b: Euler’s method applied to y′ = 2y, y(0) = 3 with step h = 0.1 and h = 0.01, compared tothe exact solution.

The function legend adds a legend. Each argument introduces a description of the corresponding curvefrom plot. The last argument controls the placement of the legend in the figure. Type help legendfor more details.

IMPORTANT REMARKWhen using 5 steps of size h = 0.1 the approximation of the exact value y(0.5) = 3e ' 8.1548 is storedin y(6). On the other hand when using 50 intervals of size h = 0.01, it is stored in y(51). To avoidconfusion both can be referenced by y(end).

1. Answer the following questions regarding what you see in Fig L2b.

Page 52: manualv2

46 MATLAB sessions: Laboratory 2

(a) What are the exact value at t = 0.5 and the corresponding Euler approximations using 5and 50 steps? Using the geometric interpretation of Euler’s method explain why both Eulerapproximations 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 errorobtained with 5 steps. Which approximation is more accurate? What is the ratio of the twoerrors? 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 confirmyour conclusions.

2. Consider the IVP y′ = −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 fork = 2, . . . , 7. Plot curves on different subplots of the same figure. What do you observe forsmall values of N (i.e., large h)? Explain the behavior of the approximation obtained forlarge N using the direction field and the graphical interpretation of Euler’s method.

Improved Euler’s Method

The improved Euler’s method is most easily described by considering the expression (L2.2). Using atrapezoidal approximation for the integral leads to

y(t1) ' y(t0) +h

2(f(t0, y(t0)) + f(t1, y(t1))) ,

i.e.,

y(t1) = y(t0) +h

2(f(t0, y(t0)) + f(t1, y(t1))) + . . . . (L2.3)

Then substitute y(t0) = y0 and define y1 ' y(t1) by removing the . . . in (L2.3):

y1 = y0 +h

2(f(t0, y0) + f(t1, y1)) . (L2.4)

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 thisproblem, 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). Theresulting quantity

y1 = y0 +h

2

(f(t0, y0) + f(t1, y0 + hf(t0, y0)︸ ︷︷ ︸

Euler y1 from (L2.1)

))

(L2.5)

with t1 = t0 + h is the improved Euler approximation. This approximation can be thought of as acorrection to the Euler approximation. The iteration (L2.4) is then repeated to obtain y2 ' y(t2), . . .,i.e.,

yn+1 = yn + h2

(f(tn, yn) + f(tn + h, yn + hf(tn, yn))

)

tn+1 = tn + h

Minor modifications are made to the function euler.m to implement the improved Euler method.

Page 53: manualv2

MATLAB sessions: Laboratory 2 47

impeuler.m

function [tout,yout] = euler(f,tspan,y0,N)% solves the IVP y’=f(t,y), y(tspan(1))=y0 up to t=tspan(2)% using improved Euler’s method with N time steps% use: impeuler(@f,[tmin,tmax],y0,N)h = (tspan(2)-tspan(1))/N;t = tspan(1); tout = t;y = y0(:); yout = y.’;for n=1:N

f1 = feval(f,t,y);f2 = feval(f,t+h,y+h*f1);y = y+h*(f1+f2)/2; t = t+h;yout = [yout; y.’]; tout = [tout; t];

end

The use of the function is similar to the use of euler.m:

>> [t,y] = impeuler(f,[0,.5],3,5); % use @f if defined in separate function>> [t,y]ans =

0 3.00000.1000 3.66000.2000 4.46520.3000 5.44750.4000 6.64600.5000 8.1081

Note that the improved Euler approximation with 5 steps is already more accurate than the Eulerapproximation with 50 steps! (hence the “improved”)

3. Consider the IVP y′ = 2y, y(0) = 3.

(a) What are the improved Euler approximations using 50, 500 and 5000 steps?

(b) Compare the errors. How is the error reduction related to the ratio of numbers of steps used?

4. Consider the IVP y′ = −2y, y(0) = 3. Determine the improved Euler approximations in theinterval 0 ≤ t ≤ 10 using N = 2k steps for k = 2, . . . , 7. Plot curves on different subplots of thesame figure. What do you observe for small values of N (i.e., large h)? Compare to the resultsobtained for Euler’s method.

Additional Problems

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

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

7. A child situated at the point (0, Y0) on the positive y-axis is dragging a toy on a string. He beginspulling the toy initially resting at (x0, 0) on the positive x-axis and walks at a constant pace vaway from the origin along the positive y-axis.

Page 54: manualv2

48 MATLAB sessions: Laboratory 2

(a) Show that the differential equation describing thetrajectory followed by the toy is

dy

dx= y′ = −

√a2 − x2

xwith y(x0) = 0

and a =√

x20 + Y 2

0 (hint: consider the angle θ andthe length of the string, see figure).

(b) Use both Euler’s and improved Euler’s methods witha = 10, x0 = 8 and N = 78 steps to obtain a numer-ical approximation for 0.2 ≤ x ≤ 8 (i.e., h = −0.1).

(c) Compare the approximations obtained to the solu-tion obtained using ode45.m. Compare the resultwith the exact solution

y(x) = Y0 −√

a2 − x2 + a ln

(x0

x

a +√

a2 − x2

a + Y0

).

.........

..............................................θ

@@

@@

@@

@

AA

AA

AA

AAA

s

s

s

s

Y0

Y

y

x x0

EEEEEE

(d) Is the trajectory independent of the velocity v? Show that x, y and t are related by

y +√

a2 − x2 = vt + Y0. (L2.6)

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

dx = −x√

a2 − x2

a2vdt.

(f) Repeat part (b) using a variable hn = −xn

√a2−x2

n

a2 vδt instead, with x0Y0a2 vδt = 0.1 (so that

h0 = h = −0.1).Note: euler.m and impeuler.m need to be modified since it is not a priori known how manysteps will be needed to reach x = 0.2. Use a while loop rather than a do loop.

(g) Compare the results with the ones obtained using a constant h. How many steps are needed?Explain why hn < h for x ' x0 and x small, but hn > h in some intermediate range of xvalues (hard).

Page 55: manualv2

MATLAB sessions: Laboratory 3 49

Laboratory 3Solution 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 (orreduced).

2. Identify situations where multiple solutions coexist.

First consider the IVP y′ = y with y(0) = 1. Let’s apply Euler’s method to obtain an approximatesolution 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.00000.1000 1.10000.2000 1.21000.3000 1.33100.4000 1.46410.5000 1.6105: :

1.5000 4.17721.6000 4.59501.7000 5.05451.8000 5.55991.9000 6.11592.0000 6.7275

>> newy0=y(end)*exp(-2) % new ICnewy0 =

0.9105>> [newt,newy]=ode45(f,t,newy0); % "exact" solution with new IC at same t>> [newt,newy]ans =

0 0.91050.1000 1.00620.2000 1.11200.3000 1.22900.4000 1.35830.5000 1.5011: :

1.5000 4.08041.6000 4.50961.7000 4.9839

Page 56: manualv2

50 MATLAB sessions: Laboratory 3

1.8000 5.50801.9000 6.08732.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 sameODE but with a different initial condition. To understand the likelihood of a numerical solution todeviate from the exact solution it is then reasonable to determine how exact solution curves are modifiedwhen the initial condition is perturbed.

Dependence of the Solution of IVPs on the Initial Condition

To determine the effect of a change δy0 in the initial condition y0 has on the solution y(t) of the IVP

y′ = f(t, y),y(t0) = y0

(L3.1)

at a fixed time, consider y as a function of t as well as y0 and differentiate (L3.1) with respect to y0. Weobtain

δy′(t) = δf(t, y(t)) =∂f

∂y(t, y(t)) δy(t) (chain rule).

On the other hand

δy′(t) = δd

dty(t) =

d

dtδy(t) = (δy)′ (derivatives commute).

Thus δy satisfies the linear ODE

(δy)′ =∂f

∂y(t, y(t)) δy (L3.2)

(assume y(t) is known). An initial condition for δy is obtained by differentiating the IC in (L3.1):

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

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

δy(t) = δy0 exp(∫ t

t0

∂f

∂y(s, y(s)) ds

). (L3.4)

The relation (L3.4) shows that a perturbation in the initial condition y0 creates a perturbation in thesolution y(t) at a later time t > t0 with an amplification factor exp

(∫ t

t0

∂f∂y (s, y(s)) ds

). It encapsulates

all significant results of interest in this laboratory session. In particular

• if ∂f∂y > 0 perturbations are amplified (a dangerous situation),

• if ∂f∂y < 0 perturbations are damped (a good situation),

• the only way to have δy(t) = 0 in regions where∫ t

t0

∂f∂y (s, y(s)) ds is bounded (e.g., where ∂f

∂y iscontinuous) is to have δy0 = 0 (exp 6= 0), i.e., trajectories starting with different initial conditionscannot cross,

• if∫ t

t0

∂f∂y (s, y(s)) ds = +∞ for some t (in particular when ∂f

∂y is not continuous) then infinitesimallysmall (0) perturbations in y0 can create finite perturbations in y(t) (“0×∞” may be finite). Thismeans that two different trajectories starting with the same initial value are possible, i.e., thesolution may not be unique if it exists (see condition for existence and uniqueness of a solution inthe Nagle/Saff/Snider text).

Two specific situations are of interest:

Page 57: manualv2

MATLAB sessions: Laboratory 3 51

1. (pure integration) For ODEs of the form y′ = f(t) (i.e., f does not explicitly depend on y) we have∂f∂y = 0 so that the relation (L3.4) becomes δy(t) = δy0. as an example consider the ODE y′ = et.The direction field and several solution curves are shown in Fig. L3a, left. The field direction (aswell as intensity) is the same for all points situated on the same vertical line t = cst. All solutionsare simple vertical translations of the same function.

2. (autonomous ODE) For ODEs of the form y′ = f(y) (i.e., f does not explicitly depend on t, suchan ODE is called autonomous) regions where f ′(y) > 0 are regions where perturbations expandand regions where f ′(y) < 0 are regions where perturbations contract. As an example consider theODEs y′ = y (f ′(y) = 1, expanding solutions) and y′ = −y (f ′(y) = −1, contracting solutions).The direction field and several solution curves are shown in Fig. L3a, center and right. The fielddirection is the same for all points situated on the same horizontal line y = cst.

−2 −1 0 1 2−4

−3

−2

−1

0

1

2

3

4

−2 −1 0 1 2−4

−3

−2

−1

0

1

2

3

4

−2 −1 0 1 2−4

−3

−2

−1

0

1

2

3

4

Figure L3a: Direction field of y′ = et (left), y′ = y (center), and y′ = −y (right) with several solutioncurves.

In general ODEs exhibit both regions where solutions contract and regions where solutions expand,as illustrated in the following problems.

1. Consider the ODE y′ = tt2−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 fort > 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) = afor a = 0, 1

2 , 1, 2. To do this complete and run the following m-file:

function lab3ex1for a = [0,1/2,1/2]

[t,y] = ode45(@f,[?,?],a); % fill in time intervalplot(t,y); hold on;

Page 58: manualv2

52 MATLAB sessions: Laboratory 3

endfunction 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 canbe 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 isnegative). What is the minimal value of t that can be reached? Describe the type of curvesobtained.

2. Consider the (nonlinear) IVP

y′ = y(1− y),y(0) = y0.

(a) Draw the direction field and solution curves corresponding to y0 = −1, 0, 12 , 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 particularsolution but also the behavior of nearby solutions, e.g. using the direction field. For example the IVPs

y′ = et,y(0) = 1 and

y′ = y,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 theerror at t = 2 obtained for both problems. Which problem is numerically better? Use also (L3.4)to support your conclusions.

Existence and Uniqueness

An extreme case of large error amplification arises when ∂f∂t in (L3.4) becomes unbounded. As an example

consider a situation where a non-negative quantity y changes with respect to time at a rate equal totwice the square root of its current value, i.e.,

dy

dt= 2

√y. (L3.5)

We recall the following existence and uniqueness result:

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

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

In the case (L3.5) we have f(t, y) = 2√

y and ∂f∂t (t, y) = 1√

y . Thus (L3.5) has a unique solutionpassing through y(0) = y0 for any y0 > 0. For y0 = 0 however, the result does not apply and thesolution is not guaranteed to be unique or even exist. In fact one can easily verify that y(t) = 0 andy(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′ = 2√

y, y(0) = 0? (hint: think of functions whichare defined piecewise).

5. Consider the IVP y′ = 2√

y, y(0) = ε > 0.

Page 59: manualv2

MATLAB sessions: Laboratory 3 53

0 0.25 0.5 0.75 10

0.25

0.5

0.75

1

Figure L3b: Direction field of y′ = 2√

y with two solutions satisfying y(0) = 0, namely y(t) = 0 andy(t) = t2. Remark: the direction field has been plotted using a nonlinear spacing in the y-direction toemphasize its behavior close to the t-axis.

(a) Is the solution guaranteed to exist? Is is unique?

(b) Verify that y(t) = (t +√

ε)2 is a solution.

(c) Use (L3.4) to show that δy(t) = δy0

(1 + t√

ε

). How does this confirm that the IVP may not

be guaranteed to have a unique solution when ε = 0?

(d) Use ode45 to obtain an approximate solution in the interval [0, 1] for ε = 0.0001. Determinethe solution starting with y(0) = ε

2 instead and compute the change in the solution at t = 1.Does this confirm the result obtained in (c)? To do this you may want to use the followingscript:

epsilon = 0.0001; y0 = epsilon;[t1,y1] = ode45(f,[0,1],y0);[t2,y2] = ode45(f,[0,1],y0/2);deltay = y1(end)-y2(end); % change in solution at t = 1deltayp = (y0/2)*(1+t1(end)/sqrt(y0)); % change predicted by formula

Page 60: manualv2

54 MATLAB sessions: Laboratory 3

Additional Problems

6. Determine whether the solution y(t) = 0 of the ODE y′ = − y1+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 closeto 0 for large t (hint: use the direction field, ode45, or (L3.4))

7. Justify why an equilibrium ye for the autonomous ODE y′ = f(y) is called a sink if f ′(ye) < 0 anda source if f ′(ye) > 0.

8. Consider the (autonomous) ODE y′ = y cos y = f(y). Examine the plot of f between −2π and 2π.Identify sources and sinks. Verify your finding by plotting the direction field.

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

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

−6

−4

−2

0

2

4

6

8

9. Consider the IVP y′ = 2√

y, y(0) = 0.

(a) What is the numerical solution obtained by applying Euler’s method? Does reducing the stepsize change the numerical solution? Repeat for the improved Euler method. What is thenumerical solution obtained by using ode45?

(b) The trapezoidal method introduced in laboratory 2 is defined by

yn+1 = yn +h

2(f(tn, yn) + f(tn+1, yn+1)) (L3.6)

for n = 0, 1, . . . Show that here (L3.6) yields yn+1 =(

h2 +

√yn + h

√yn

)2(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) = ??; % completet(1) = 0; tf = 2; N = 10; h = (tf-t0)/N;for n = 1:N

y(n+1) = ??; % completet(n+1) = t(n)+h;

endplot(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 explicitmethods in obtaining solutions of problems with large ∂f

∂y ?

Page 61: manualv2

MATLAB sessions: Laboratory 3 55

10. Consider the IVP y′ = y1/3, y(0) = 0. Verify that y(t) = 2√

69 t3/2 is a solution for t ≥ 0. Identity

two other solutions for t ≥ 0.

Page 62: manualv2

56 MATLAB sessions: Laboratory 4

Laboratory 4Picard 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 numericalapproximations. 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 comparedto standard procedures (Euler, ode45,...)

Primary MATLAB commands used in this laboratory are ode45 and interp1.

Picard iteration

The Initial Value Problem y′ = f(t, y),y(t0) = y0

involves y on both sides of the ODE. If an approximation φ0 of the solution y is known, then y′ ' f(t, φ0).Using the initial condition we get

y(t) ' y0 +∫ t

t0

f(s, φ0(s)) ds (L4.1)

(recall that y′ = g(t) with y(t0) = y0 is equivalent to y(t) = y0 +∫ t

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

φ1(t) = y0 +∫ t

t0

f(s, φ0(s)) ds. (L4.2)

(L4.2) is equivalent to φ′1 = f(t, φ0),φ1(t0) = y0.

(L4.3)

The process can be repeated, defining a sequence φnn≥0 of approximations to the exact solution y:

φn+1(t) = y0 +∫ t

t0

f(s, φn(s)) ds, n = 0, 1, . . . (L4.4)

or, equivalently, φ′n+1 = f(t, φn),φn+1(t0) = y0,

n = 0, 1, . . . (L4.5)

The iteration (L4.4/L4.5) is called Picard (fixed point) iteration. Whether φn(t) → y(t) as n increasesand for what range of t values depends in general on the problem (L4.1) considered (i.e., f , y0), andon the choice of initial approximation φ0(t). Without additional knowledge about the solution y(t) theinitial 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, whichdetermine approximations for increasing values of t starting from t0.

Page 63: manualv2

MATLAB sessions: Laboratory 4 57

One of the main applications of Picard’s method is in the proof of existence and uniqueness of thesolution for first-order initial value problems, under certain conditions of f . This proof is not consideredhere. Instead we illustrate how the method works on a few examples in order to gain some understandingof the method. In some cases this method provides a valuable tool to evaluate numerical solutions thateven sophisticated numerical solvers fail to identify.

We start with a simple example: consider the IVP y′ = y with y(0) = 1. We set φ0(t) = 1. Then

φ′1 = φ0, φ1(0) = 1 ⇒ φ1(t) = 1 +∫ t

0φ0(s) ds = 1 +

∫ t

0ds = 1 + t,

φ′2 = φ1, φ2(0) = 1 ⇒ φ2(t) = 1 +∫ t

0φ1(s) ds = 1 +

∫ t

0(1 + s) ds = 1 + t + 1

2 t2,

φ′3 = φ2, φ3(0) = 1 ⇒ φ3(t) = 1 +∫ t

0φ2(s) ds = 1 +

∫ t

0(1 + s + 1

2s2) ds = 1 + 12 t2 + 1

6 t3,

φ′4 = φ3, φ4(0) = 1 ⇒ φ4(t) = 1 +∫ t

0φ3(s) ds = 1 +

∫ t

0(1 + t 1

2 t2 + 16 t3) ds = 1 + 1

2 t2 + 16 t3 + 1

24 t4,. . .

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

φn(t) =n∑

k=0

tk

k!→

∞∑

k=0

tk

k!= et (Taylor series of et).

Numerical Picard Iteration

One question is: how do we obtain the approximations φn numerically? There are two ways to answerthis 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 numbernpts of points ti. The corresponding values of φn+1(ti) are then obtained from (L4.4) via theupdate

φ1(ti) = φ1(ti−1) +∫ ti

ti−1

f(s, φ0(s)) ds, i = 1, . . . , npts, (L4.6)

with φ1(t0) = y0. In order to determine φ2 quadl must be able to evaluate φ1 anywhere usinginterpolation based on the points (ti, φ1(ti)) obtained, via the MATLAB function interp1 (seethe 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 atintermediate points when (L4.5) is solved for n = 1.

The numerical Picard iteration is illustrated in Fig. 3. MATLAB implementations of both versions arealso included.

The first version (based on quadl) requires to set the number npts of points, while the secondversion (based on ode45) does not. More importantly, the first version is less efficient, in part becauseof the evaluation of (3) inside a loop (the MATLAB routine quadl cannot evaluate multiple integralssimultaneously). It also handles exceptions (e.g. when reaching a vertical asymptote in the solution)less gracefully than the second version.

Page 64: manualv2

58 MATLAB sessions: Laboratory 4

φn(t) φn+1(tj)

s ss

s

s

s

φn+1(t)¶¶

­­··

¢¢

quadlor ode45-

interp1-

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

picard1.m (quadl version)

function [t,y] = picard1(f,t,y,N)% Picard iteration using quadlTOL = 1e-6; % default, reset if desiredz = y(1)*ones(size(t));for k=2:N

z(k) = z(k-1)+quadl(@fint,t(k-1),t(k),TOL,[],f,t,y);endy = z;%-------------------------------------------------------function dydtint = fint(t,f,told,yold)% ODE rhs interpolated at t from (told,yold)dydtint = feval(f,t,interp1(told,yold,t,’spline’));

Lab4a.m (quadl version)

function Lab4atspan = [0,3]; yspan = [0,20]; y0 = 1; N = 10;window = [tspan,yspan]; t = tspan;npts = 100; % #pts for integrationt = linspace(tspan(1),tspan(2),npts);y = feval(@init,t,y0);plot(t,y,’r’,’LineWidth’,2);hold on;for n = 1:N

[t,y] = picard1(@f,t,y,npts);plot(t,yint,’r’,’LineWidth’,2);

enddirfield(@f,window,’arrow’); % direction field, see Lab1[t,y] = ode45(@f,tspan,y0); % "exact" solutionplot(t,y,’b’,’LineWidth’,2); % plot "exact" solutionhold offaxis(window)%---------------------------------------------------function dydt = f(t,y) % ODEdydt = y;%---------------------------------------------------function y = init(t,y0)% initialization for Picard iteration.y = y0*ones(size(t)); % standard. If modified, make% sure the new function satisfies the IC

picard2.m (ode45 version)

function [t,y] = picard2(f,t,y)% Picard iteration using ode45options = odeset(’RelTol’,1e-6,’AbsTol’,1e-6);[t,y] = ode45(@fint,t([1,end]),y(1),options,f,t,y);%----------------------------------------------------function dydtint = fint(t,y,f,told,yold)% ODE rhs interpolated at t from (told,yold)dydtint = feval(f,t,interp1(told,yold,t,’spline’));

Lab4b.m (ode45 version)

function Lab4atspan = [0,3]; yspan = [0,20]; y0 = 1; N = 10;window = [tspan,yspan]; t = tspan;teval = linspace(tspan(1),tspan(2),100);y = feval(@init,t,y0);plot(t,y,’r’,’LineWidth’,2);hold on;for n = 1:N

[t,y] = picard2(@f,t,y);yint = interp1(t,y,teval,’spline’);plot(teval,yint,’r’,’LineWidth’,2);

enddirfield(@f,window,’arrow’); % direction field, see Lab1[t,y] = ode45(@f,tspan,y0); % "exact" solutionplot(t,y,’b’,’LineWidth’,2); % plot "exact" solutionhold offaxis(window)%---------------------------------------------------function dydt = f(t,y) % ODEdydt = y;%---------------------------------------------------function y = init(t,y0)% initialization for Picard iteration.y = y0*ones(size(t)); % standard. If modified, make% sure the new function satisfies the IC

The (common) output of Lab4a.m/Lab4b.m is shown in Fig. L4b. The direction field (see Laboratory1) has been superposed to check the validity of the approximation.

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

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

Page 65: manualv2

MATLAB sessions: Laboratory 4 59

0 0.5 1 1.5 2 2.5 30

2

4

6

8

10

12

14

16

18

20

Figure L4b: Picard iterates φ1, . . . , φ10 starting with φ0(t) = 1 for the IVP y′ = y, y(0) = 1.

(a) Determine algebraically (as in page 57) the iterates φ1, . . . , φ4, starting with φ0(t) = 1. Whatis the expected limit of the sequence φnn≥0?

(b) Use the ode45 version of the MATLAB implementation of Picard’s iteration to obtain thefirst 10 iterates in the window 0 ≤ t ≤ 3 (use the range 0 ≤ y ≤ 1 for plotting). Explain whythe iterates alternate above/below the exact solution.

3. The problem y′ = 2t− y2, 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 ≤ 1for 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 iteratesthe same? Use tic ... toc to time the computation of successive iterate. What do younotice?

Additional problems

4. Generate algebraically several Picard iterates for the initial value problem y′ = 2t(y + 1), y(0) = 0and determine to which function they converge. Check your calculation numerically using picard.mand by solving the IVP analytically.

5. Show that if y(t) = y0 is a (constant) solution to the IVP y′ = 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 tothe IVP y′ = f(t, y), y(0) = y0, then φn(t) = y(t) for n > 0 if φ0(t) = y(t) (i.e., a solution remainsa solution!)

Page 66: manualv2

60 MATLAB sessions: Laboratory 4

6. Consider the IVP y′ = 2√

y, y(0) = 0.

(a) Determine algebraically (as in page 57) the iterates φn for n > 0 when starting with φ0(t) = 0.

(b) Use the ode45 version of the MATLAB implementation of 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 forplotting).

7. Consider the IVP y′ = 1 + y2, 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 numberof 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 forplotting).

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

Page 67: manualv2

MATLAB sessions: Laboratory 5 61

Laboratory 5Applications 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 totime. This section looks at some examples of this modelling. Our objectives are as follows.

1. Use differential equations in modelling changes in population by means of the exponential, logistic,and modified logistic population models.

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

3. Use differential equations to model mixing problems.

Population Growth

Exponential growth

A simple way of modelling the growth (or decline) of a population N is to assume that the rate of changein the population at any time t is proportional to the quantity N(t) that is present (or remaining).Formally, this rate is change is

dN

dt= rN. (L5.1)

Separating variables and solving for N(t) with initial value N(t0) = N0 yields the exponential functionN(t) = N(t0)er(t−t0). The proportionality constant r is the difference in the per capita birth and deathrates (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 whilerapidly 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 maximumsustainable population size (also called carrying capacity) of the habitat of study. Then Nmax−N is thenumber of new individuals that the habitat can accept and Nmax−N

Nmaxthe 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

dt= rN

Nmax −N

Nmax= rN

(1− N

Nmax

)= rN − cN2 (L5.2)

with c = r/Nmax. Equation (L5.2) succinctly shows that logistic population growth is the combinationof the process of inhibited growth with the process of competition among pairs of individuals at a ratec.

Page 68: manualv2

62 MATLAB sessions: Laboratory 5

Modified logistic growth

We can modify the logistic equation (L5.2) by including the possibility that when the population size istoo small, say less than Nmin, the inability to find a suitable mate leads to the extinction of the species.The modified logistic equation (also called Nagumo equation) is

dN

dt= rN

(1− N

Nmax

) (N

Nmin− 1

). (L5.3)

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

Effect of stocking/harvesting

We can expand upon either model by adding (to model stocking) or subtracting (to model harvestingor hunting) an amount α > 0 for each time period. For example a logistic model with harvesting reads

dN

dt= rN

(1− N

Nmax

)− α.

Problems

1. Generate the direction fields of the exponential, logistic, and modified logistic models for populationgrowth and record any observable differences. Use Nmax = 20, Nmin = 10, r = 0.8. What are thelong 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 accordingto 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 logisticmodel with r = 0.3 and Nmax = 3000. Assume that initially there are 2500 fishes of that speciesin the lake. Determine the correct IVP for each of the scenarios below and in each case determinefrom 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 ODEdirfield(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 therewill 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 pastthirteen years. We wish to determine the model which represents the behavior of this populationbest:

year 1 2 3 4 5 6 7 8 9 10 11 12 13population 34 40 46 51 55 58 60 62 63 63 64 64 64

>> years = 1:13; population = [34,40,46,51,55,58,60,62,63,63,64,64,64];>> plot(years,population,’.r’,’MarkerSize’,20)

Page 69: manualv2

MATLAB sessions: Laboratory 5 63

0 2 4 6 8 10 12 1430

35

40

45

50

55

60

65

(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 theabove table and the value y(ti) computed use ode45 for a specific guess of the parameter(s).

Evaluate the quantity13∑

i=1

(yi − y(ti))2. If your result is much larger than 0.878 adjust your

parameter(s) (say to 3 decimal digits).

(f) Does it make sense to have a model giving a non-integer population size?

Other Models, Parameter Estimation

Differential equations similar to population models can be used to model other phenomena such asheating/cooling, spread of diseases, and mixing problems. Here are three examples.

5. Newton’s law of cooling states that the rate dTdt at which the temperature T of an object

changes with time is proportional to the difference of temperature between the object and theambient medium. Mathematically we write

dT

dt= k

(Tair − T

).

Milk is brought out of a refrigerator compartment kept at 40 degrees into a warm room of unknowntemperature. After 4 minutes the temperature of the milk is 54 degrees and after 6 minutes thetemperature of the milk is 59 degrees.

Page 70: manualv2

64 MATLAB sessions: Laboratory 5

(a) What is the temperature of the room? For this you may want to use the following program:

function lab5pb5tdata = [4;6]; Tdata = [54;59]; % data time/temperaturek = ??; Tair = ??; % fill in initial guessparam = fminsearch(@F,[k;Tair],[],tdata,Tdata); % optimal solutionk = 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 thecommands

[t,T] = ode45(@f,[0,20],40,[],k,Tair);i = find(T>Tair-1); t(i(1))

6. Spread of Disease. Suppose that an infectious disease is spreading among a population ofN individuals. For simplicity we will assume that the incubation period is zero and that thechanges in the progress of the decease are continuous. The population is comprised of 3 types ofindividuals: infected (i individuals), susceptible (s individuals), and removed (r individuals, eitherimmune, dead, or removed into isolation). Susceptible individuals can become infected at a rateproportional to both susceptible and infected population sizes si (a second-order rate of change).Infected individuals become removed at a rate proportional to the infected population size only (afirst-order rate of change).

s -a i -b r

Accordingly, the following equations hold:

ds

dt= −asi,

di

dt= asi− bi,

dr

dt= bi. (L5.4)

Note that ddt (s + i + r) = 0, i.e., s + i + r = cst = N . From (L5.4) one easily obtain

di

ds=

asi− bi

−asi=

b/a

s− 1, (L5.5)

giving the rate of change of infected individuals with respect to those susceptible.

(a) Solve analytically (L5.5) for i in terms of s. Use an IC i(s0) = i0.

(b) Graph the solution for particular choices of b/a, s0, and i0. Use the following commands:

f = inline(’??/s-1’,’s’,’i’); % choose constant b/ai0 = ??; s0 = ??; % select IC[s,i] = ode45(f,[i0,2],s0); % forward solutionplot(s,i); hold on;[s,i] = ode45(f,[i0,1e-3],s0); % backward solutionplot(s,i); hold off;

What do the graphs tell us about the relationship between the population size of infectedindividuals versus the population size of susceptible individuals?

Page 71: manualv2

MATLAB sessions: Laboratory 5 65

7. Mixing Problem (§3.2). Suppose a brine solution containing 2 kg of salt per liter runs into a tankinitially filled with 500 liters of water containing 50 kg of salt. The brine runs into the tank at arate of 5 liters/min. The mixture, kept uniform by stirring, is flowing out at a rate of 5 liters/min.

rout = 5 `/mcout = c(t)

-

rin = 5 `/mcin = 2 kg/`

-

volumeV (t)

concentrationc(t)

(a) Find the concentration c(10), in kg/`, of salt in the tank after 10 minutes. Hints: note thatthe volume is constant; identify the rate of change ds

dt of the amount of salt s(t) in terms ofrin, rout, cin, and c(t) and express c(t) in terms of s(t) to obtain an ODE in s(t). Use thefollowing 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 calculatedin (a). Moreover the volume of the tank is now decreasing. Use the following MATLABcommands:

ode2 = inline(’10-6*s/(510-t)’,’t’,’s’); % explain the ODE[t2,s2] = ode45(ode1,[10,??],s1(end)); % fill-in final timeconcentration2 = s2(end)/(510-??)

What happens at t = 510 min? What is the maximal amount of salt that was in the tank atany 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 ofthe 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 leakdevelops compared to the situation in (b)? Why?

(d) Plot the concentration c(t) for 0 ≤ t ≤ 510 for all scenarios.

Page 72: manualv2

66 MATLAB sessions: Laboratory 6

Laboratory 6Further Applications of First-Order Differential Equations

(Project B of Ch. 2/Ch. 3 of the Nagle/Saff/Snider text)

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

The Snowplow Problem(see page 84 of the Nagle/Saff/Snider text)

One morning it began to snow very hard and continued snowing steadily throughout the day. A snowplowset 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 additionalmile 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 functionsof time t (measured in hours). Using t = 0 for 8:00 A.M. the problem specifies the following:

p(0) = 0, p(2) = 2, p(4) = 3.

Moreover s(−T ) = 0 for some T > 0 (t = −T is the time it started to snow relative to 8:00 A.M.)

t = −T

9 A.M. (t = 0)

11 A.M. (t = 2)

1 P.M (t = 4)

- p

6s

To construct a model for this problem, we must consider the rate of snow accumulation and the rateof the snowplow. We will assume that it is snowing at a constant rate (steadily) and also that the rate atwhich the snowplow can clear the road is inversely proportional to the height of the snow being cleared.Thus,

ds

dt= a and

dp

dt=

b

s(L6.1)

where a and b are positive constants.

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

2. Show that T satisfies the nonlinear equation

ln(1 + 2

T

)

ln(1 + 4

T

) =23.

3. Determine T by plotting an appropriate function or using the following MATLAB commands:

Page 73: manualv2

MATLAB sessions: Laboratory 6 67

eq = inline(’??’,’T’); % fill-in equation in the form ?? = 0guess = ??; % fill-in initial guess for TT = fzero(eq,guess)

At what time (in the form ?:?? A.M.) did it start to snow? What is the value of the ratio ba?

More realistically the rate at which the snowplow can clear the road is inversely proportional to theweight of the snow being cleared, i.e., to the height times the density of the snow. As the snow piles upit becomes more compact and we assume that the density is an increasing linear function ρ(t) = 1 + αt.

4. Derive a differential equation model similar to (L6.1) for p = p(t).

5. Solve the model and show that T satisfies the nonlinear equation

ln(1 + 2

T

)− ln(1 + 2α)ln

(1 + 4

T

)− ln(1 + 4α)=

23.

6. Plot T as a function of α for 0 ≤ α ≤ 0.5 using the following MATLAB commands:

function lab6pb6A = []; 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];

endplot(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 beused? At what time (in the form ?:?? A.M.) did it start to snow if α = 0.1?

7. What happens for α & 0.809?

Aircraft Guidance in a Crosswind(see Project C, Ch. 3, page 146 of the Nagle/Saff/Snider text)

An aircraft flying under the guidance of a nondirectional beacon (a fixed radio transmitter, abbreviatedNDB) moves so that its longitudinal axis always points toward the beacon. The pilot sets out towardan NDB from a point at which the wind is at right angles to the initial direction of the aircraft. Thewind maintains this direction. Assume the wind speed w and the speed a of the aircraft through the air(its airspeed) remain constant.

¦¦ -

6

x

y

¡¡

¡¡¡ª6

©©©©¼A

T

W6

W

Page 74: manualv2

68 MATLAB sessions: Laboratory 6

We place the start of the flight at (2,0) and the destination at (0,0). Let

T =

[dxdt

dydt

], W =

[0w

], A = α

[xy

]

denote the velocity tangent relative to the ground (tangent to the trajectory), the wind vector, and thevelocity 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 signof α.

9. The vectors T, W, and A are such that T = A + W. By identifying the components on bothsides of this equation, show that the trajectory y = y(x) satisfies the ODE

dy

dx=

y

x− γ

√x2 + y2

x

for x > 0, where γ = w/a.

10. Plot solutions corresponding to γ = 0, .2, .5, .9, .99 using the following MATLAB commands:

function lab6pb10gamma = ??; % select gammax0 = ??; y0 = ??; % fill in initial conditionxf = 1e-3;[x,y] = ode45(@f,[x0,xf],y0,[],gamma);plot(x,y);axis equal; axis([0,2,0,1])%-------------------------------------function dydx = f(x,y,gamma)dydx = ??; % fill in ODE

What happens as γ gets closer to 1? What happens (physically) when γ ≥ 1?

11. For small x show that the ODE becomes dydx ' (1 − γ) y

x . Deduce that y(x) ' x1−γ for small x.Verify this numerically by plotting y = y(x) in log-log scale (i.e., use loglog instead of plot).

Heating and Cooling of Buildings(see §3.3, page 101, of the Nagle/Saff/Snider text)

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

dT

dt= k(Tout − T ) + ku(T ∗ − T ). (L6.2)

The constants k and ku are proportionality constants in Newton’s law of cooling, Tout represents theoutside temperature, and T ∗ is a temperature set by a furnace or air conditioning unit (in degreesFahrenheit). We assume that daily variations of the outside air temperature are modelled by

Tout = 80− 15 cos(

πt

12

).

The temperature T ∗ is set such that k(Tout−Td)+ku(T ∗−Td) = 0 for a desired temperature Td, whereTout is the daily average outside temperature.

12. Show that (L6.2) can be written

dT

dt= k(Tout − Tout) + (k + ku)(Td − T ).

Page 75: manualv2

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 lab6pb12ku = 1;Toutave = mean(feval(@Tair,1:24)); Td = 75;k = 0.5;[t,T] = ode45(@f,[0,48],70,[],k,ku,Toutave,Td);plot(t,T,’b-+’);k = 0.25;[t,T] = ode45(@f,[0,48],70,[],k,ku,Toutave,Td);hold on; plot(t,T,’r-o’); hold off;legend(’k=0.5’,’k=0.25’)grid on; set(gca,’XTick’,0:6:48)%----------------------------------------------function dTdt = f(t,T,k,ku,Toutave,Td)Tout = feval(@Tair,t);dTdt = (k+ku)*(Td-T)+k*(Tout-Toutave);%----------------------------------------------function Tout = Tair(t)Tout = 80-15*cos(pi*t/12);

0 6 12 18 24 30 36 42 4870

71

72

73

74

75

76

77

78

79

80k=0.5k=0.25

Figure L6a: T (t) for two values of k.

13. Which value of k represents the better insulation? Why? See what happens if there is a greateror lesser variation of outside temperature. Write your conclusions. Is this model realistic?

Page 76: manualv2

70 MATLAB sessions: Laboratory 6

Improved Model

A more realistic modeldT

dt= k(Tout − T ) + U (L6.3)

is obtained with constant rates U = 8 units/hour of heat if T < Td and U = −6 units/hour of coolingif T > Td + 1. In between Td and Td + 1 there is no artificial heating or cooling. To solve this new setupwe start with T (0) = 70 degrees and heat the building up to a small amount dT above Td, or cool itdown to −dT below Td. We use k = 0.25. The following MATLAB procedure implements this scenariotogether with the previous one and plots the outside temperature for comparison.

function lab6pb12a% basic modelku = 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 modeloptions = 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);

endplot(allt,allT,’b’,’LineWidth’,1); hold off;legend(’outside’,’first model’,’improved model’)grid on; set(gca,’XTick’,0:6:48)%------------------------------------------------function [v,term,dir] = events(t,T,k,U,Td,dT)v = (T-(Td-dT))*(T-(Td+dT)); term = 1; dir = 1;%------------------------------------------------function dTdt = f(t,T,k,ku,Toutave,Td)Tout = feval(@Tair,t);dTdt = (k+ku)*(Td-T)+k*(Tout-Toutave);%------------------------------------------------function dTdt = fi(t,T,k,U,Td,dT)Tout = feval(@Tair,t);dTdt = k*(Tout-T)+U;%------------------------------------------------function Tout = Tair(t)Tout = 80-15*cos(pi*t/12);

14. Which strategy is the most comfortable?

15. Explain why the oscillations in the new model are more spaced when the outside temperature ishigh (daytime).

Page 77: manualv2

MATLAB sessions: Laboratory 6 71

0 6 12 18 24 30 36 42 4865

70

75

80

85

90

95outsidefirst modelimproved model

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

16. Reduce the size of U to see the effect. What does this mean from a practical point of view withregards 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.

18. (hard) The energy consumed is E1 =∫ 48

0ku|T ∗ − T (t)|dt for the first model and E2 =

∫ 48

0|U |dt

for the second. Which strategy uses the most energy?

Page 78: manualv2

72 MATLAB sessions: Laboratory 7

Laboratory 7Implementing 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 beobtained using the same MATLAB commands as in the first-order by rewriting the ODE in the form ofa system of first order ODEs.Our objectives in this laboratory are as follows:

1. Learn how to reduce a higher-order IVP to a first-order system

2. Learn how to implement a higher-order/system ODE in MATLAB using ode45.m and euler.m.

3. Get some proficiency in analyzing and comparing solutions for different but similar problems.

Reducing a Higher-Order ODE(see §5.2, page 243, of the Nagle/Saff/Snider text)

Let’s start with an example. Consider the IVP

d2y

dt2+ 4

dy

dt+ 3y = cos t, with y(0) = −1,

dy

dt(0) = 0. (L7.1)

To reduce the order of the ODE we introduce the intermediate unknown function v = dydt . As a result

dvdt = d2y

dt2 so that the ODE can be written dvdt + 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. ForMATLAB implementations it is necessary to write these ODEs in the form d∗

dt = . . .. Thus

d2y

dt2+ 4

dy

dt+ 3y = cos t ⇔

dydt = v,

dvdt = cos t− 4v − 3y.

(L7.2)

Initial conditions from (L7.1) must also be transformed into initial conditions for y and v. Simply,

y(0) = −1,dy

dt(0) = 0 ⇔

y(0) = −1,

v(0) = 0.(L7.3)

We are now ready to implement the IVP in MATLAB.

MATLAB Implementation

The following code shows how to solve the IVP (L7.1) for 0 ≤ t ≤ 12 using the MATLAB routine ode45.

function lab7ex1t0 = 0; tf = 12; % initial and final timesy0 = -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 Yfigure(1); plot(t,y,’b+-’,t,v,’ro-’); % time series for y and vlegend(’y(t)’,’v(t)=y’’(t)’); grid on % note the use of ’’ for ’figure(2); plot(y,v); % phase plotxlabel(’y’); ylabel(’v=y’’’); grid on%------------------------------------

Page 79: manualv2

MATLAB sessions: Laboratory 7 73

function dYdt = f(t,Y)y = Y(1); v = Y(2);dYdt = [ v ; cos(t)-4*v-3*y ];

Note how the initial conditions are specified in the calling sequence of ode45, in the form of an array[y0,v0] ([y0;v0] is also valid). The routine ode45 returns a vector t containing the times in theinterval [0, 4] at which the solution was computed, and a matrix Y with two columns of the same lengthas t, one for each of y and v (in that order). Note how the approximations for y and v are retrievedfrom Y.

The time series for both y and v are plotted in the MATLAB figure window 1, and the phase plotshowing v vs y is done in the figure window 2.

0 2 4 6 8 10 12−1

−0.8

−0.6

−0.4

−0.2

0

0.2

0.4

0.6

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

−1 −0.8 −0.6 −0.4 −0.2 0 0.2 0.4−0.4

−0.2

0

0.2

0.4

0.6

0.8

1

y

v=y’

Figure L7a: Time series y = y(t) and v = v(t) = y′(t) (left), and phase plot v = y′ vs. y for (L7.1).

1. (a) For what (approximate) value(s) of t is y reaches a local maximum in the window 0 ≤ t ≤ 12?Check by reading the Y matrix.

(b) What seems to be the long term behavior of y?

(c) Modify the initial conditions. Does the long term behavior of the solution change? If yes inwhat way?

2. Implement the IVP y′′ + 2y′ + y = cos t with y(0) = y′(0) = 0. Plot both time series of y and y′

and the phase plot y′ vs y. Describe the behavior of the solution y (in particular in the long term).

Additional Considerations

Using euler.m

The routine euler.m described page 44 can be used without modification to find an approximate solutionfor (L7.1):

function lab7ex2t0 = 0; tf = 12; % initial and final timesy0 = -1; v0 = 0; % initial conditions% ode45 solution[t,Y] = ode45(@f,[t0,tf],[y0,v0]);y = Y(:,1); v = Y(:,2);% Euler solutionh = 0.1; N = round((tf-t0)/h);[te,Ye] = euler(@f,[t0,tf],[y0,v0],N);

Page 80: manualv2

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 vlegend(’ode45’,’Euler’); grid onfigure(2); plot(y,v,’b+-’,ye,ve,’ro-’); % phase plotxlabel(’y’); ylabel(’v=y’’’); grid onlegend(’ode45’,’Euler’); grid on%------------------------------------function dYdt = f(t,Y)y = Y(1); v = Y(2);dYdt = [ v ; cos(t)-4*v-3*y ];

For comparison the solution y obtained with ode45 is included in the plot, see Figure L7b.

0 2 4 6 8 10 12−1

−0.8

−0.6

−0.4

−0.2

0

0.2

0.4ode45Euler

−1 −0.8 −0.6 −0.4 −0.2 0 0.2 0.4−0.4

−0.2

0

0.2

0.4

0.6

0.8

1

y

v=y’

ode45Euler

Figure L7b: Time series y = y(t) (left) and phase plane v = y′ vs. y (right) obtained from ode45.m andeuler.m for the problem (L7.1).

3. Solve the problem (L7.1) using the improved Euler method from page 47. Compare the resultswith those obtained from ode45 and euler.

Nonlinear Problems

Nonlinear problems do not present any additional difficulty from an implementation point of view (theymay present new numerical challenges for integration routines like ode45). As an example consider themodified problem

d2y

dt2+ 4y2 dy

dt+ 3y = cos t, with y(0) = −1,

dy

dt(0) = 0. (L7.4)

The ODE (L7.4) is very similar to (L7.1) except for the y2 term in the left-hand side. Because of thefactor y2 the ODE (L7.4) is nonlinear, while (L7.1) is linear. There is however very little to changein the implementation of (L7.1) to solve (L7.4). The driver part lab7ex1 is not modified (same initialconditions) while the ODE definition becomes

function dYdt = f(t,Y)y = Y(1); v = Y(2);dYdt = [ v ; cos(t)-4*y^2*v-3*y ];

The new output is shown in Fig L7c.

4. (a) Compare the output of Figs L7a and L7c. Describe the changes in the behavior of the solutionin the short term.

Page 81: manualv2

MATLAB sessions: Laboratory 7 75

0 2 4 6 8 10 12−1.5

−1

−0.5

0

0.5

1

1.5

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

−1 −0.8 −0.6 −0.4 −0.2 0 0.2 0.4 0.6 0.8−1.5

−1

−0.5

0

0.5

1

1.5

2

y

v=y’

Figure L7c: Time series y = y(t) and v = v(t) = y′(t) (left), and phase plot v = y′ vs. y for (L7.4).

(b) Increase the time interval of computation. Compare the long time behavior of both problems(L7.1) and (L7.4), in particular the amplitude of oscillations.

5. Solve numerically the IVP

d2y

dt2+ 4|y|dy

dt+ 3y = cos t, with y(0) = −1,

dy

dt(0) = 0

in the interval 0 ≤ t ≤ 12. Is the behavior of the solution significantly different from that of thesolution of (L7.4)? Comment. In particular, compare the size of the long term oscillations in ywith that of the problems (L7.1) and (L7.4).

6. Solve numerically the IVP

d2y

dt2+ 4y

dy

dt+ 3y = cos t, with y(0) = −1,

dy

dt(0) = 0

in the interval 0 ≤ t ≤ 12. Is the behavior of the solution significantly different from that of thesolution of (L7.4)? Comment.

A Third-Order Problem

Consider the third-order IVP

d3y

dt3+ 4y2 d2y

dt2+ 8y

(dy

dt

)2

+ 3dy

dt= − sin t, with y(0) = −1,

dy

dt(0) = 0,

d2y

dt2(0) = 4. (L7.5)

Introducing v = dydt and w = dy2

dt2 we obtain dvdt = w and dw

dt = d3ydt3 = − sin t−4y2w−8yv2−3v. Moreover,

v(0) = dydt (0) = 0 and w(0) = d2y

dt2 (0) = 4. Thus (L7.5) is equivalent to

dydt = v,

dvdt = w,

dwdt = − sin t− 4y2w − 8yv2 − 3v

with

y(0) = −1,

v(0) = 0,

w(0) = 4.

(L7.6)

This problem is implemented as follows.

function lab7ex3t0 = 0; tf = 12; % initial and final times

Page 82: manualv2

76 MATLAB sessions: Laboratory 7

y0 = -1; v0 = 0; w0 = 4; % initial conditions[t,Y] = ode45(@f,[t0,tf],[y0,v0,w0]);y = Y(:,1); v = Y(:,2); w = Y(:,3); % extract y, v, w from Yfigure(1);plot(t,y,’b+-’,t,v,’ro-’,t,w,’mx-’); % time serieslegend(’y(t)’,’v(t)=y’’(t)’,’w(t)=y’’’’’); % note the use of ’grid on; ylim([-1.5,2]);figure(2); plot3(y,v,w); % 3D phase plotxlabel(’y’); ylabel(’v=y’’’); zlabel(’w=y’’’’’); grid on%-------------------------------------------------------function dYdt = f(t,Y)y = Y(1); v = Y(2); w = Y(3);dYdt = [ v ; w; -sin(t)-4*y^2*w-8*y*v^2-3*v ];

The output is shown in Fig. L7d. The limit is the vertical axis of the plot on the left were deliberately setto the same ones as in Fig. L7c for comparison purposes using the MATLAB command ylim([-1.5,2]).

0 2 4 6 8 10 12−1.5

−1

−0.5

0

0.5

1

1.5

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

−1−0.8

−0.6−0.4

−0.20

0.20.4

0.60.8

−1.5

−1

−0.5

0

0.5

1

1.5

2

−4

−2

0

2

4

yv=y’

w=

y’’

Figure L7d: Time series y = y(t), v = v(t) = y′(t), and w = w(t) = y′(t) (left), and 3D phase plot v = y′

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

7. (a) Compare the output of Figs L7c and L7d. What do you notice?

(b) 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 thesolutions identical? Comment.

Alternate Reduction

The choice of intermediate function v in the reduction of (L7.1) to first-order ODEs is not limited tov = dy

dt , although it is the simplest from a practical point of view. Other choices may be used, whichmay be more revealing from a purely mathematical point of view or lead to more accurate numericalresults.

To reduce (L7.1) to a set of two first-order ODEs consider for example the choice v = dydt + y, i.e.,

dydt = v − y. Then

dv

dt=

d2y

dt2+

dy

dt=

(cos t− 4

dy

dt− 3y

)+

dy

dt= cos t− 3(v − y)− 3y = cos t− 3v. (L7.7)

Page 83: manualv2

MATLAB sessions: Laboratory 7 77

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

v(0) =dy

dt(0) + y(0) = 0 + (−1) = −1. (L7.8)

Thus

(L7.1) ⇔

dydt = v − y,

dvdt = cos t− 3v

with

y(0) = −1,

v(0) = −1.(L7.9)

Note that (L7.7) is independent of y and can be integrated directly, either analytically here, or numeri-cally, for v. The solution y can then be obtained from v by direct integration or numerical quadrature.

8. Solve (L7.9) numerically using ode45:

(a) by solving the problem as a system;

(b) by first solving numerically for v (use only (L7.8) and (L7.9)), then use the following MATLABcommands to obtain y:

% assume v was obtained as [tv,v] = ode45(...)[ty,y] = ode45(@odey,[0,12],??,[],tv,v); % fill-in IC...%---------------------------------------function dydt = odey(t,y,tv,ty)v = interp1(tv,ty,t); % interpolate vdydt = v-y;

(c) Compare the solutions with the one obtained using v = y′.

9. Is there any other value of r such that the choice v = dydt − ry leads to an ODE in v which is

independent of y?

Page 84: manualv2

78 MATLAB sessions: Laboratory 8

Laboratory 8The 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-springsystem with differential equations.

Our objectives are as follows:

1. Determine the effect of parameters on the solutions of differential equations.

2. Determine the behavior of the mass-spring system from the graph of the solution.

3. Determine the effect of the parameters on the behavior of the mass-spring.

The primary MATLAB commands use are the ode45 function and the masspring.m GUI.

Mass-Spring System without Damping

The motion of a mass suspended to a vertical spring can be described as follows. When the spring isnot loaded it has length `0 (situation (a)). When a mass m is attached to its lower end it has length `(situation (b)). From the first principle of mechanics we then obtain

mg︸︷︷︸downward weight force

+ −k(`− `0)︸ ︷︷ ︸upward tension force

= 0. (L8.1)

The term g measures the gravitational acceleration (g ' 9.8m/s2 ' 32ft/s2). The quantity k is a springconstant measuring its stiffness. We now pull downwards on the mass by an amount y and let the massgo (situation (c)). We expect the mass to oscillate around the position y = 0. The second principle ofmechanics yields

mg︸︷︷︸weight

+ −k(` + y − `0)︸ ︷︷ ︸upward tension force

= md2(` + y)

dt2︸ ︷︷ ︸acceleration of mass

, i.e., md2y

dt2+ ky = 0 (L8.2)

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

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

y

`

`0

m

k

γ

Page 85: manualv2

MATLAB sessions: Laboratory 8 79

Equation (L8.2) is rewrittend2y

dt2+ ω2y = 0 (L8.3)

where ω2 = k/m. Equation (L8.3) models simple harmonic motion. A numerical solution with ini-tial conditions y(0) = 0.1 meter and y′(0) = 0 (i.e., the mass is initially stretched downward 10cmsand released, see setting (c) in figure) is obtained by first reducing the ODE to first-order ODEs (seeLaboratory 7).

Let v = y′. Then v′ = y′′ = −ω2y = −4y. Also v(0) = y′(0) = 0. The following MATLAB programimplements the problem (with ω = 2).

function lab8ex1m = 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<10y = Y(:,1); v = Y(:,2); % retrieve y, v from Yfigure(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 ω = 2directly in the function f. The advantage is that its value can easily be changed in the driver part of theprogram rather than in the function, for example when multiple plots with different values of ω need tobe compared in a single MATLAB figure window.

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

−0.15

−0.1

−0.05

0

0.05

0.1

0.15

0.2

Figure L8a: Harmonic motion

Page 86: manualv2

80 MATLAB sessions: Laboratory 8

1. From the graph in Fig. L8a answer the following questions.

(a) Which curve represents y = y(t)?

(b) What is the period of the motion?

(c) When will the mass-spring system come to rest? Why?

(d) What is the amplitude of the oscillations for y?

(e) What is the maximum velocity attained by the mass, and when is it attained?

(f) How does the size of the mass m and the stiffness k of the spring affect the motion?

2. (a) Plot the quantity E = 12mv2 + 1

2ky2 as a function of time. What do you observe?

(b) Show analytically that dEdt = 0.

(c) Plot v vs y (phase plot). Does the curve ever get close to the origin?

Mass-Spring System with Damping

When the movement of the mass is damped due to viscous effects (e.g., the mass moves in a cylindercontaining oil, situation (d)), an additional term proportional to the velocity must be added. Theresulting equation becomes

md2y

dt2+ γ

dy

dt+ ky = 0 or

d2y

dt2+ c

dy

dt+ ω2y = 0 (L8.4)

by setting c = γ/m. The program lab8ex1 is updated by modifying the function f:

function lab8ex1am = 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<10y = Y(:,1); v = Y(:,2); % retrieve y, v from Yfigure(1); plot(t,y,’b+-’,t,v,’ro-’); % time series for y and v%-------------------------------------------function dYdt = f(t,Y,omega,c)y = Y(1); v = Y(2);dYdt = [ v ; ?? ]; % fill-in dv/dt

3. From the graph in Fig. L8b answer the following questions.

(a) For what minimal time t1 will the mass-spring system satisfy |y(t)| > 0.01 for all t > t1? Youcan answer the question either by magnifying the MATLAB figure using the magnify button

, or use the following MATLAB commands (explain):

for i=1:length(y)m(i)=max(abs(y(i:end)));

endi = find(m<0.01); i = i(1);disp([’|y|<0.01 for t>t1 with ’ num2str(t(i-1)) ’<t1<’ num2str(t(i))])

(b) What is the maximum velocity attained by the mass, and when is it attained?

(c) How does the size of γ affect the motion?

(d) Determine the smallest (critical) value of c (or γ) such that no oscillation appears in thesolution. Demonstrate your result numerically.

Page 87: manualv2

MATLAB sessions: Laboratory 8 81

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

−0.15

−0.1

−0.05

0

0.05

0.1

0.15

0.2y(t)v(t)=y’(t)

Figure L8b: Damped harmonic motion

4. (a) Plot the quantity E = 12mv2 + 1

2ky2 as a function of time. What do you observe?

(b) Show analytically that dEdt < 0 for γ > 0 while dE

dt > 0 for γ < 0.

(c) Plot v vs y (phase plot). Comment on the behavior of the curve.

The GUI masspring.m

The GUI masspring.m is a simple to use Graphical User Interface (written in MATLAB but this is trans-parent to the user) useful for understanding how the solution of the mass-spring problem changes whenphysical parameters such as the mass m, the friction coefficient γ, the spring constant k, the initial condi-tions y(0) and y′(0), are varied. The GUI is currently available at http://math.asu.edu/∼bdw/PUBLIC.After download the GUI is launched in the MATLAB Command Window by entering

>> masspring

A new window which looks like Fig. L8c opens. The parameters can be changed in the edit boxes atthe top of the window. The solve button then solves the problem. The solution is displayed inthe lower left part of the window. If the parameters are changed and the problem solved again the axesin the display are likely to change. To keep the previous axes, press the hold on button . Torelease the axes, press the button again (now labelled hold off).

The GUI has two nice features.

• Parameters can be continuously changed within a predefined range. To select which parameter

Page 88: manualv2

82 MATLAB sessions: Laboratory 8

Figure L8c: The GUI masspring.m

to change select the appropriate item in the menu . Then use the slider

by continuously clicking on one of the directional arrows (left or right) orsimply moving the slider left or right while pressing the left mouse button. The solution is thencontinuously updated in the graph area. It is recommended to set the hold button for this feature,in order to better understand how changes in the parameter affect the solution.

• The actual physical movement of the mass can be observed for a given setting of the parameters bypressing the play button . At the same time a red marker moves on the trajectory displayed inthe graph area on the left to indicate the point on the solution curve corresponding to the currentelongation of the spring on the right. The current time is also displayed. The movement can bepaused using the button .

Finally the button resets parameter values to default values, while the button exitsthe GUI.

5. Experiment with the GUI. In particular, review problems 1 through 4.

Note that the GUI masspring.m also handles forced vibrations, see Laboratory 10.

Page 89: manualv2

MATLAB sessions: Laboratory 9 83

Laboratory 9The 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 thedownward positive vertical y-axis. Positive angles are oriented counter-clockwise, in the direction of thepositive x-axis.

?y

-x

qc.................................

..............

..............................................................................................................

...............................................

.....................................

.......................................................................................................................................................................................................................

..........................................................

@@

@@

@@

@@y

T

F

A

W

m@

@@

@I

¡¡

¡¡

¡¡µ

¡¡ª

?

The position of the mass m is (x, y) = (` sin θ, ` cos θ). The firstprinciple of mechanics states that the acceleration vector A isthe sum of all forces applied to the mass, namely the weightW, the tension in the rod T, and the friction force F oppositeto the movement and proportional to the velocity of the mass.Thus

A = W + F + T (L9.1)

with

A = md2

dt2

[xy

]= m`

d2θ

dt2

[cos θ− sin θ

]−m`

(dθ

dt

)2 [sin θcos θ

],

W =[

0mg

], F = −γ

d

dt

[xy

]= −γ`

dt

[cos θ− sin θ

],

(g ' 9.8 m/s2 ' 32 ft/s2) and

T ∝[xy

]∝

[sin θcos θ

]

(only the direction of T is known, not the magnitude).

When taking the dot product of (L9.1) with[

cos θ− sin θ

]the contribution of T disappears (this amounts

to projecting (L9.1) onto a direction perpendicular to the direction of the rod, i.e., in the direction of Aor F). This yields

m`d2θ

dt2= −mg sin θ − γ`

dt, or

d2θ

dt2+ c

dt+ ω2 sin θ = 0 (L9.2)

with c = γ/m and ω2 = g/`. Clearly, equation (L9.2) is nonlinear, which makes it interesting to studysince no analytical solution is available.

Our objectives are as follows.

1. Determine the effect of variations in the parameters in the solution.

2. Determine the effect of “linearization” of the differential equation.

The Undamped Case

Let’s first assume that c = 0 (i.e., γ = 0). We solve the ODE (L9.2) subject to initial conditionsθ(0) = 45 degrees and θ′(0) = 1 rad/s, assuming ` = 0.5 m. The ODE is first reduced to a set of twofirst-order ODEs

dt= v,

dv

dt= −ω2 sin θ (L9.3)

with v(0) = θ′(0) = 0.5 rad/s. A MATLAB implementation follows.

Page 90: manualv2

84 MATLAB sessions: Laboratory 9

function lab9ex1g = 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<10theta = Y(:,1); % retrieve thetafigure(1); plot(t,theta*180/pi,’b-’); % theta in degreesgrid on%-----------------------------------------------function dYdt = f(t,Y,omega)theta = Y(1); v = Y(2);dYdt = [ ?? ; ?? ]; % fill-in ODE

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

−40

−30

−20

−10

0

10

20

30

40

50

Figure L9a: Motion of a simple pendulum: θ = θ(t) (degrees).

1. From the graph in Fig. L9a answer the following questions.

(a) What is the period of the motion?

(b) Will the pendulum come to rest? Why?

(c) What is the maximal angle the pendulum makes with the vertical?

(d) Does the value of the mass m affect the plot?

2. Change the initial condition on the rate of change of θ to v(0) = 8.17 rd/s, v(0) = 8.175 rd/s, andv(0) = 8.18 rd/s. Decide whether the behavior makes sense. How is the motion of the pendulummodified compared to the previous situation? The following graph shows the case v(0) = 8.17 rd/s.

Page 91: manualv2

MATLAB sessions: Laboratory 9 85

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

−150

−100

−50

0

50

100

150

200

3. Use the following options in ode45:

options = odeset(’Reltol’,1e-12,’AbsTol’,1e-12’);[t,Y] = ode45(@f,[0,20],[theta0,v0],options,omega);

Redo question 2. What has changed in the numerical procedure?

4. Try some of the following variations on the initial conditions:

(a) θ(0) = π rad, θ′(0) = 0 rad/s.

(b) θ(0) = 227 rad, θ′(0) = 0 rad/s.

(c) θ(0) = π rad, θ′(0) = 30 rad/s.

(d) θ(0) = 2π rad, θ′(0) = 1 rad/s.

(e) θ(0) = 10π rad, θ′(0) = 0 rad/s.

(f) θ(0) = 2207 rad, θ′(0) = 0 rad/s.

(g) θ(0) = −7π rad, θ′(0) = 0.03 rad/s.

(h) θ(0) = −7π rad, θ′(0) = 0.01 rad/s.

Comment on the behavior of the pendulum in each case. Are any of the behaviors realistic? Areany of the behaviors not realistic? If so what is the explanation for the unrealistic behavior?

5. (a) Plot the quantity E = 12m`

(dθdt

)2+mg(1−cos θ) as a function of time. What do you observe?

(b) Show analytically that dEdt = 0.

(c) Plot v vs θ (phase plot). How does the curve behave?

Page 92: manualv2

86 MATLAB sessions: Laboratory 9

The Linearized Case

Let’s know examine what happens when we substitute θ for sin θ in (L9.2). The new equation for θ isthus

d2θ

dt2+ ω2θ = 0. (L9.4)

6. Modify the function implementing the ODE accordingly and plot both linearized and originalsolutions together. Experiment with the following initial conditions and summarize what happens.

(a) θ(0) = 0 degree, θ′(0) = 2 rad/s.

(b) θ(0) = 0 degree, θ′(0) = 50 rad/s.

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

(d) θ(0) = 45 degrees, θ′(0) = 8.17 rad/s.

(e) θ(0) = 45 degrees, θ′(0) = 8.18 rad/s.

(f) θ(0) = 180 degrees, θ′(0) = 30 rad/s.

(g) θ(0) = 360 degrees, θ′(0) = 0 rad/s.

For each case make a judgment whether the graph accurately describes the movement of thependulum. Which of the graphs exhibit significant discrepancies between original and linearizedcases? Can you explain why?

With Damping Present

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

7. First reduce the ODE (L9.2) to a system of two first-order ODEs similar to (L9.3). Modify theexample lab9ex1 accordingly.

function lab9ex2g = ??; l = ??; m = ??; gamma = ??;omega = ??; c = ??;theta0 = ??; v0 = ??; % pay attention to degrees vs radiansoptions = odeset(’Reltol’,??,’AbsTol’,??’);[t,Y] = ode45(@f,[0,20],[theta0,v0],options,omega,c);theta = Y(:,1);figure(1); plot(t,??,’b-’); % theta in degreesgrid 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 eachcase 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 remainsthe same).

Page 93: manualv2

MATLAB sessions: Laboratory 9 87

(a) θ(0) = 45 degrees, θ′(0) = 1 rad/s.

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

−30

−20

−10

0

10

20

30

40

50

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

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

−50

0

50

100

150

200

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

0 2 4 6 8 10 12 14 16 18 20150

200

250

300

350

400

450

500

550

Page 94: manualv2

88 MATLAB sessions: Laboratory 9

8. The Poe pendulum(Poe’s Pendulum by Borelli, Coleman & Hobson, Mathematics Magazine, 58(2) (1985) 78-83)

Do problem 7 first. Assume that we have now a pendulum with a length increasing over time inthe form

` = `(t) = `0(1 + αt)

where α is a positive constant. The ODE modelling the rate of change of θ now becomes

d2θ

dt2+ c

dt+

ω2

1 + αtsin θ = 0 (L9.5)

Compare the behavior of the Poe pendulum when α = 1 and for the values from problem 7. Foreach of the 3 cases of initial values, plot the solution for the Poe pendulum compared to the solutionfrom problem 6. What is the general change in the frequency of oscillations? What happens if thefriction term c vanishes for the initial conditions θ(0) = 45 degrees, θ′(0) = 1 rad/s? Make surethat you integrate the differential equation over a sufficiently large time interval.

Page 95: manualv2

MATLAB sessions: Laboratory 10 89

Laboratory 10Forced 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 concentrateon equations with a periodic harmonic forcing term. This will lead to a study of the phenomenon knownas resonance. The equation we consider has the form

d2y

dt2+ c

dy

dt+ ω2y = sin Ωt. (L10.1)

This equation models the movement of a mass-spring system similar to the one described in Laboratory8 page 78. The forcing term on the right-hand side of (L10.1) models a vibration, with amplitude 1 andfrequency ω (in radians per second = 1

2π rotation per second = 602π rotations per minute, or RPM) of

the plate holding the mass-spring system. All physical constants are assumed to be positive.When c

2 < ω the general solution of (L10.1) is

y(t) = ae−12 ct sin

(t

√ω2 − c2

4+ φ

)+ A sin (Ωt + ϕ) (L10.2)

withA =

1√(ω2 − Ω2)2 + c2Ω2

, (L10.3)

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). Thefirst 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 objectivesof this laboratory are then to understand

1. the effect of the forcing term on the behavior of the solution for different values of ω, in particularon the amplitude of the solution.

2. the phenomena of resonance and beats in the absence of friction.

The Amplitude of Forced Oscillations

We assume here that ω = 2 and c = 1 are fixed. Initial conditions are set to 0. For each value of Ω, theamplitude A can be obtained numerically by taking half the difference between the highs and the lowsof the solution computed with a MATLAB ODE solver after a sufficiently large time, as follows:

1 function lab10ex12 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;

Page 96: manualv2

90 MATLAB sessions: Laboratory 10

9 t1 = 25; i = find(t>t1);10 A = (max(Y(i,1))-min(Y(i,1)))/2;11 disp([’computed amplitude of forced oscillation = ’ num2str(A)]);12 Atheory = 1/sqrt((omega^2-Omega^2)^2+(c*Omega)^2);13 disp([’theoretical amplitude = ’ num2str(Atheory)]);14 %----------------------------------------------------------------15 function dYdt = f(t,Y,param)16 y = Y(1); v = Y(2);17 omega = param(1); c = param(2); Omega = param(3);18 dYdt = [ v ; sin(Omega*t)-omega^2*y-c*v ];

When executing this program we get

>> lab10ex1computed amplitude of forced oscillation = 0.51163theoretical amplitude = 0.51181

Lines 9-13 deserve some explanation. Line 9 defines a time t1 after which we think the contribution ofthe first term in (L10.2) has become negligible compared to the second term. This depends of courseon the parameter values, in particular c. With c = 1 we obtain e−

12 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 valueslarger than t1 is then determined. The quantity Y(i,1) refers to the values of y associated to timeslarger than t1 only. The computed amplitude is simply half the difference between the max and the minvalues. This value is compared to the theoretical value (L10.3).

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

−0.6

−0.4

−0.2

0

0.2

0.4

0.6

y

Figure L10a: Forced oscillation.

1. (a) What is the frequency (in radians per second) of the forced oscillation? What is the numericalvalue (modulo 2π) of the angle ϕ defined by (L10.4)?

Page 97: manualv2

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 anexponentially decreasing oscillation?

(c) Divide the resulting function obtained in (b) by e−12 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 withthe expression (L10.2)?

2. We now consider A as a function of Ω. We use again ω = 2, c = 1 and y(0) = y′(0) = 0. Theprevious problem determined A for a specific value of Ω. Here we consider a range of values forΩ and determine numerically the corresponding amplitude A. Plot the result as a function. Youmay need the following MATLAB program.

function lab10ex2omega = 2; c = 1;OMEGA = ??; A = zeros(size(OMEGA)); % fill-int0 = 0; y0 = 0; v0 = 0; Y0 = [y0;v0]; tf = 50; t1 = 25;for k = 1:length(OMEGA)

Omega = ??; % fill-inparam = [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;

endAtheory = ??; % fill-infigure(1)plot(??); grid on; % fill-inxlabel(’\Omega’); ylabel(’A’);%----------------------------------------------------------------function dYdt = f(t,Y,param)y = Y(1); v = Y(2);omega = param(1); c = param(2); Omega = param(3);dYdt = [ v ; sin(Omega*t)-omega^2*y-c*v ];

1 1.2 1.4 1.6 1.8 2 2.2 2.4 2.6 2.8 30.15

0.2

0.25

0.3

0.35

0.4

0.45

0.5

0.55

Ω

A

Plot also the theoretical amplitude A from (L10.3) as a function of Ω. For what approximate valueof Ω is the amplitude of the forced oscillation maximal? Is this value comparable to the value

Page 98: manualv2

92 MATLAB sessions: Laboratory 10

obtained from (L10.3)? (Hint: differentiate...) Are the results affected by changes in the initialconditions?

Resonance

We now investigate what happens to the solution (L10.2), and more specifically to the maximal amplitudeA of the forced oscillation, when we let c → 0. The value of Ω corresponding to this maximal amplitudeis called resonant frequency. When a mechanical system is stimulated by an external force operating atthis frequency the system is said to be resonant.

4. Repeat problem 2 with c = 0.

1 1.2 1.4 1.6 1.8 2 2.2 2.4 2.6 2.8 30

5

10

15

20

25

30

Ω

A

computed numericallytheoretical

Explain what happens. What is the maximal amplitude? What is the frequency Ω yielding themaximal 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 oftwo sine functions. When Ω is close to the resonant frequency some interesting phenomenon, known asbeats, 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).

Page 99: manualv2

MATLAB sessions: Laboratory 10 93

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

−2

−1.5

−1

−0.5

0

0.5

1

1.5

2

2.5

y

Explain what happens. What is the period of the fast oscillation? What is the period of the slowoscillation? How do these values vary as Ω moves closer to the resonant frequency? moves awayfrom the resonant frequency?

Additional Problem

5. Experiment with the GUI masspring.m mentioned in Laboratory 8 page 81. In particular setthe parameter button ) to frequency and move the slider ) to visualize thechange in the solution when other parameters are set to values from the above examples.

.

Page 100: manualv2

94 MATLAB sessions: Laboratory 11

Laboratory 11Analytical and Graphical Analysis of Systems

(§5.1, 5.2, 5.4 and §9.1-9.6 of the Nagle/Saff/Snider text)

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

dx

dt= ax + by,

dy

dt= cx + dy

(L11.1)

where a, b, c, and d are real constants. The system (L11.1) is written in matrix form

dxdt

= Ax with x =[xy

]and A =

[a bc d

]. (L11.2)

The objectives of this laboratory are as follows.

1. Learn how to use MATLAB to find eigenvalues and corresponding eigenvectors to build the solutionof the ODE system (L11.1).

2. Learn how to use MATLAB to graph and interpret the phase plane for the system (L11.1).

3. Compare the system (L11.1) to equivalent systems.

Primary MATLAB commands used in this laboratory are eig, null, dirfield.

An Example(§9.5 of the Nagle/Saff/Snider text)

Consider the matrix A =[1 42 −1

]. The eigenvalues are the roots of the characteristic equation p(λ) =

det(A − λI) = 0. The characteristic polynomial of A can be obtained in MATLAB with the commandpoly. The eigenvalues are then computed by computing the roots of this polynomial:

>> A = [1,4;2,-1]A =

1 42 -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 eacheigenvalue λ, or, equivalently, find the set of vectors x satisfying (A− λI)x = 0 (I is the 2× 2 identity

matrix I =[1 00 1

]). This set is called the nullspace of the matrix A − λI. This can be done via

MATLAB’s null command:

Page 101: manualv2

MATLAB sessions: Laboratory 11 95

>> I = eye(2,2) % define 2x2 identity matrixI =

1 00 1

>> lambda1 = evalues(1) % first eigenvaluelambda1 =

3>> x1 = null(A-lambda1*I)x1 =

0.89440.4472

Thus x =[0.89440.4472

]is an eigenvector of A associated to eigenvalue λ = 3 (in fact any nonzero multiple of

this vector is also an eigenvector associated to eigenvalue 3). A quick numerical verification shows thatAx and λx match to machine accuracy.

>> A*x1-lambda1*x1ans =

1.0e-015 *0

-0.4441

1. Determine the eigenvector of A associated to the second eigenvalue of A.

In practice eigenvalues and eigenvectors of A are computed using a safer and more efficient procedureimplemented in the MATLAB eig command:

>> A = [1,4;2,-1]A =

1 42 -1

>> evalues = eig(A)evalues =

3-3

>> [S,Lambda] = eig(A)S =

0.8944 -0.70710.4472 0.7071

Lambda =3 00 -3

When specifying a single output eig returns all eigenvalues in a vector with as many entries as thedimension of A. To get the corresponding eigenvectors one simply use two output arguments: thefirst one is a matrix S whose columns are the eigenvectors x1 and x2 of A, i.e., S =

[x1|x2

]. The

second matrix is a diagonal matrix Λ (read “lambda”) whose diagonal coefficients are the corresponding

eigenvalues, i.e., Λ =[λ1 00 λ2

]. In this case the eigenvalues are referenced in MATLAB as Lambda(1,1)

and Lambda(2,2).

2. The MATLAB command inv(S) determines the matrix inverse S−1 of S. Compute the matrixproduct S−1ΛS. Do you recognize the resulting matrix? Can you explain algebraically why thisresult can be expected?

3. In this problem it is possible to find eigenvectors with integer entries. Do it. Now S is a matrixwith integer entries. What is S−1ΛS?

Page 102: manualv2

96 MATLAB sessions: Laboratory 11

We now turn to the solution of the differential system (L11.2) (i.e., (L11.1)). From the theory we knowthat the solution is

x(t) = C1eλ1tx1 + C2e

λ2tx2 (L11.3)

where C1 and C2 are constants defined from the initial conditions. At t = 0 we obtain

x(0) = C1x1 + C2x2 =[x1|x2

] [C1

C2

]= S

[C1

C2

]. (L11.4)

Given the initial vector x(0), the constants C1 and C2 can be obtained by solving the system (L11.4).

If x(0) = 1 and y(0) = 0 then x(0) =[10

].

>> x0 = [1;0]; C = inv(S)*x0C =

0.7454-0.4714

or, better, as

>> x0 = [1;0]; C = S\x0C =

0.7454-0.4714

4. Write a MATLAB program to evaluate the expression (L11.3). Plot x and y as functions of t andy vs x in the interval 0 ≤ t ≤ 2. Compare with the direct solution of (L11.1) using ode45.

Phase Plot

A phase plot is a direction field of the ODE dydx = . . .. From (L11.1) we obtain

dy

dx=

dy/dt

dx/dt=

cx + dy

ax + by.

The following MATLAB commands show how to obtain the phase plot.

>> f=inline(’(2*x-y)./(x+4*y)’,’x’,’y’)f =

Inline function:f(x,y) = (2*x-y)./(x+4*y)

>> dirfield(f,[-2,2,-2,2],’line’)Warning: Divide by zero.> In C:\matlabR12\toolbox\matlab\funfun\inlineeval.m at line 13In C:\matlabR12\toolbox\matlab\funfun\@inline\feval.m at line 34In 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) havealso been plotted.NOTE: if dirfield is used with the option ’arrow’ rather than ’line’ the direction of the arrowsmay 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 initialconditions to confirm your choice.

Page 103: manualv2

MATLAB sessions: Laboratory 11 97

−2 −1.5 −1 −0.5 0 0.5 1 1.5 2

−2

−1.5

−1

−0.5

0

0.5

1

1.5

2

Figure L11a: Phase plot with eigenvector directions for the matrix A=[1,4;2,-1].

6. Choose a smaller or larger window for plotting the phase plot. Does the resulting graph change?Can you give a reason why?

7. Can you explain why MATLAB complains when using dirfield with the specified window? Canyou select a window so that these remarks disappear. You may need to refer to the file dirfield.mpage 38.

Multiple Eigenvalue

In some cases the 2 × 2 matrix A in (L11.2) has a double eigenvalue λ1 = λ2 but only one eigenvectorx1, so that a matrix S cannot be constructed as above. Instead we find a vector y satisfying

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

The vector y is called a generalized eigenvector. It can be shown that (L11.5) always has infinitely manysolutions, defined up to a multiple of the eigenvector x1. The general solution of (L11.2) is then formedas the combination

x(t) = C1eλ1tx1 + C2e

λ1t (tx1 + y) , (L11.6)

where C1 and C2 are constants defined from the initial conditions.

For example consider the matrix A =[−1 1

0 −1

]. The eigenvalues/eigenvector of A are obtained

with the MATLAB eig function:

Page 104: manualv2

98 MATLAB sessions: Laboratory 11

>> A = [-1,1;0,-1]A =

-1 10 -1

>> [S,Lambda] = eig(A)S =

1.0000 -1.00000 0.0000

Lambda =-1 00 -1

The columns of the array S are, to the accuracy of the calculation, collinear. As a result S is singularand 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.50360 4.5036

The phase plot of the ODE system is shown below. Note that only the line segments line up with theorigin 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 13In C:\matlabR12\toolbox\matlab\funfun\@inline\feval.m at line 34In 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 constantsC1 and C2 computed from initial conditions x(0) = 1 and y(0) = 0. Compare the solution tothe direct solution obtained with ode45.

(b) The IVP solved in this case isdx

dt= −x + y,

dy

dt= −y, with x(0) = 1 and y(0) = 0. First

solve explicitly for y = y(t) and substitute in the ODE fordx

dt, then solve for x = x(t). Does

the solution match the results obtained in (a)?

9. Find another matrix A with double eigenvalue λ1 = λ2 = −1 and a single eigenvector (direction)x1. Plot the phase plot. Discuss the behavior of the solutions as time increases (Hint: discussaccording to the position of the initial condition in the phase plot).

Page 105: manualv2

MATLAB sessions: Laboratory 11 99

−2 −1.5 −1 −0.5 0 0.5 1 1.5 2

−2

−1.5

−1

−0.5

0

0.5

1

1.5

2

Figure L11b: Phase plot with eigenvector direction for the matrix A=[-1,1;0,-1].

Complex Eigenvalues

The characteristic polynomial of A is a quadratic polynomial with real coefficients. In some cases itsroots (i.e., the eigenvalues of A) are complex (and conjugate of each other, i.e., they are positionedin the complex plane symmetrically with respect to the real axis). In this case it can be shown thatthe corresponding eigenvectors are complex and conjugate as well. If the initial conditions are real thesolution of the problem (L11.1) must be real. The question is: how can we extract the solution from thecomplex eigenvector information using (L11.3)?

Let A =[−1 6−4 6

]. As before we first compute the eigenvalues and eigenvectors of A:

>> A = [-1,6;-4,6]A =

-1 6-4 6

>> [S,Lambda] = eig(A)S =

0.7746 0.77460.4518 + 0.4425i 0.4518 - 0.4425i

Lambda =2.5000 + 3.4278i 0

0 2.5000 - 3.4278i

Page 106: manualv2

100 MATLAB sessions: Laboratory 11

The phase plot for this problem is drawn as before and shown in Figure L11c. Note that none of theline 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 13In C:\matlabR12\toolbox\matlab\funfun\@inline\feval.m at line 34In C:\Documents and Settings\...\BDW\2003\BOOK\dirfield.m at line 9

>> axis equal tight

−2 −1.5 −1 −0.5 0 0.5 1 1.5 2

−2

−1.5

−1

−0.5

0

0.5

1

1.5

2

Figure L11c: Phase plot with eigenvector direction for the matrix A=[-1,6;-4,-6].

10. What is the direction of the flow in Figure L11c?

11. Determine the solution of the initial value problem (L11.1) with x(0) = 1 and y(0) = 1 using theexpression (L11.3). The resulting quantity is a complex vector for each value of t. Plot the realand imaginary parts separately (on two different axes). What is the solution of the IVP? Doesthis solution match the phase plot in Figure L11c? How does the solution compare to a directnumerical simulation of (L11.1) using ode45?

Page 107: manualv2

MATLAB sessions: Laboratory 11 101

Additional Problems

12. Verify numerically Euler’s formula eit = cos t + i sin t.

13. Use MATLAB to compute the eigenvalues and corresponding eigenvectors, draw the phase plane(2D example only) and set up the solution for the given initial conditions, for the following prob-lems.

(a) A =[2 −62 1

], x(0) =

[10

].

(b) A =

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

, x(0) =

112

. (Use plot3 to plot the solution)

(c) A =

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

, x(0) =

112

. (Use plot3 to plot the solution)

14. Convert the second-order linear ODE y′′+3y′+2y = 0 into a set of two first order linear ODEs anduse MATLAB to compute the eigenvalues, eigenvectors, and plot the phase plane of the resultingODE system (matrix). What happens to the solution when t →∞?

15. Consider the ODE system (L11.2) with A =[

2 −1−1 2

]. Compute eigenvalues, eigenvectors and

plot the phase plane. What can you say about the direction of eigenvectors?

16. (matrix exponential) The solution of the problem (L11.2) can be written in the form

x(t) = etAx(0),

where etA is the matrix exponential of the matrix tA. Use the MATLAB function expm to obtain

the solution with initial condition x(0) =[10

]. Compare with the solution computed by applying

directly ode45 to (L11.1).

Page 108: manualv2

102 MATLAB sessions: Laboratory 12

Laboratory 12Additional 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 solvingscalar 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 problemintroduced 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 thevalue of a step-size needed to reach a given accuracy.

• Apply the ideas to problems where accuracy is important such as those arising in celestial mechan-ics.

Taylor and Runge-Kutta Methods

The first step of Euler’s method for solving the IVP y′ = f(t, y) with y(t0) = y0 can be interpreted byconsidering the truncation of the Taylor series expansion to first-order terms, namely

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

If instead we truncate the expansion after two terms we obtain

y(t1) = y(t0 + h)

' y(t0) + hy′(t0) +h2

2y′′(t0)

= y0 + hf(t0, y0) +h2

2

(∂f

∂t(t0, y0) +

∂f

∂t(t0, y0)f(t0, y0)

)≡ y1. (L12.1)

Equation (L12.1) defines the first step of the Taylor method of order 2.taylor.m

function [tout,yout] = taylor(f,ft,fy,tspan,y0,N)% solves the IVP y’=f(t,y), y(tspan(1))=y0 up to t=tspan(2)% using Taylor’s method of order 2 with N time steps% use: taylor(@f,@ft,@fy,[tmin,tmax],y0,N)h = (tspan(2)-tspan(1))/N;t = tspan(1); tout = t;y = y0(:); yout = y.’;for n=1:N

k = feval(f,t,y);y = y+h*k+(h^2)/2*(feval(ft,t,y)+feval(fy,t,y)*k); t = t+h;yout = [yout; y.’]; tout = [tout; t];

end

Page 109: manualv2

MATLAB sessions: Laboratory 12 103

As an example consider the IVP

y′ = −10(y − e−t) + e−t, y(0) = 1

with exact solution y(t) = e−t. We compute the numerical solution at t = 1 using various step sizesh = 0.1, 0.01, 0.001, and 0.0001. We compare the accuracy obtained with both Euler’s method andTaylor’s method of order 2. The following MATLAB program is used.

function lab12ex1t0 = 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

>> lab12ex1with h=0.1 Euler error=0.0019667 Error Taylor=-0.00014735with h=0.01 Euler error=0.00020357 Error Taylor=-7.1902e-007with h=0.001 Euler error=2.0427e-005 Error Taylor=-6.8477e-009with 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 valueof p for Euler’s method? for Taylor’s method? (Hint: determine how the error decreases fora 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? Howdoes 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 useto 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.’;

Page 110: manualv2

104 MATLAB sessions: Laboratory 12

for n=1:Nk1 = 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 ofthis method?

3. What are the advantages of rk4 compared to taylor?

Application to a System of ODEs

The movement of an aircraft flying under the guidance of a nondirectional beacon was described inLaboratory 6, page 67. The equations defining the rate of change of the position of the aircraft are givenby

dx

dt= − ax√

x2 + y2

dy

dt= a

(γ − y√

x2 + y2

) (L12.2)

We now use both euler.m and rk4.m to obtain a numerical approximation to the solution of this systemwith a = 1, γ = 0.7 and x(0) = 2, y(0) = 0, on the interval 0 ≤ t ≤ 3.9, and compare them to thesolution obtained by ode45.m.

function lab12ex2t0 = 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 equalhold 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 whenthe final time is increased to 3.95. What is the reason? Do euler.m and rk4.m have thisproblem?

(b) Evaluate the accuracy of the solution at time t = 2 in both x and y directions when varyingthe step size.

Page 111: manualv2

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 asatellite around the earth) is described by the second-order system

d2x

dt2= − x

r3

d2y

dt2= − y

r3

with r =√

x2 + y2. (L12.3)

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

(a) Reduce the system of ODEs (L12.3) to a system of 4 first-order ODEs. Specify appropriateinitial conditions.

(b) Write a file kepler.m which solves the system using euler, rk4, and ode45 and plots eachsolution y vs. x (use axis equal).

(c) Plot the angular momentum M = xdydt − y dx

dt as a function of t for all three methods. Is thisquantity 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 differentialequations

d2x

dt2= x + 2

dy

dt− (1− a)

x + a

r31

− ax− 1 + a

r32

d2y

dt2= y − 2

dx

dt− (1− a)

y

r31

− ay

r32

with

r1 =√

(x + a)2 + y2

r2 =√

(x− 1 + a)2 + y2

with a = 0.012277471. The initial conditions are x(0) = 0.994, y(0) = 0, x′(0) = 0 and y′(0) =−2.00158510637908252240537862224. Plot the orbit by computing the solution using euler, rk4and ode45 in the time interval 0 ≤ t ≤ 30. What happens to the solutions? (compare to the exacttrajectory below)

−1.5 −1 −0.5 0 0.5 1 1.5−1.5

−1

−0.5

0

0.5

1

1.5

Earth

Moon

Page 112: manualv2

106 MATLAB sessions: Laboratory 12

14. (Lorenz system) The Lorenz equations

dx

dt= 10(y − x)

dy

dt= 28x− y − xz

dz

dt= xy − 8

3z

were originally extracted from a bigger atmospheric model to bring in evidence the chaotic natureof the model.

(a) Simulate the system in the interval 0 ≤ t ≤ 100 using euler, rk4 and ode45. Start with theinitial conditions x(0) = −8, y(0) = 8, z(0) = 27. Plot x as a function of t. Plot y vs. x andz vs. x.

(b) How is the time series of x modified if the initial condition is slightly changed? if the timestep/the accuracy used is changed?

Page 113: manualv2

MATLAB sessions: Laboratory 13 107

Laboratory 13Introduction to SIMULINK

In this laboratory we revisit the mass-spring system from Laboratory 8 and show how to create SIMULINKmodels for simulating its dynamics. SIMULINK is essentially a Graphical User Interface for MATLABdesigned to facilitate the integration of models using a block diagram system engineering approach andclick-and-drag mouse operations. Simulation results can be seen on the fly. In addition, you can changeparameters 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 withSIMULINK.

2. Use SIMULINK to quickly visualize the numerical solution and test the outcome of changes inparameters.

An Example SIMULINK Model: spring1.mdl

In order to get a feeling of how a SIMULINK model operates and what it can do open the spring1.mdlmodel by typing entering the MATLAB command spring1 (make sure the current directory containsthe file spring1.mdl), of clicking either on the file icon or the file name in the Current Directory panein the MATLAB window. A new window appears, see Figure L13a.

Figure L13a: The spring1 SIMULINK model.

Page 114: manualv2

108 MATLAB sessions: Laboratory 13

Figure L13b: Details of the SIMULINK spring1 model.

The spring1 model includes a source (Sine Wave ) and a sink (Scope ) for visualizing results.Parameters defining the Sine Wave can be obtained by clicking on the Sine Wave block. The fourparameters defining the function f(t) = sin(ωt + ϕ) are

• the amplitude A

• the frequency ω in radians per second (not rotation per second or minute)

• the phase shift ϕ in radians

• a sampling time used to updated the evaluation of the Sine Wave (set to 0 for continuous)

Here A = 1, ω = 1, and ϕ = π2 , so that f(t) = sin

(t + π

2

)= cos t.

The source function f(t) feeds into a summation block with 3 input ports and one output port. Notethat the other two ports have a negative sign so that the two other inputs are actually subtracted ratherthan added. Let’s call the input above z1, the one below z2, and the output of the block z, for now, seeFigure 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′ isthe output of the first block and

z = y′′. (L13.2)

Following now the feedback loops above and below, we encounter a Gain block of the form (here thedirection has been flipped). These blocks are simply multipliers by the indicated value. Note that theGain block above has input y′ while the Gain block at the bottom has input y. We have thus

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

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

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

Equation (L13.4) is a second-order linear differential equation modelling the displacement of a massm = 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 respectiveblocks. Appropriate initial condition for (L13.4) can also be set by clicking on each Integrator block .In our case the initial conditions were set to

y(0) = 1 (right integrator) and y′(0) = 0 (left integrator).

The output Scope input port is y. To visualize this output first run the simulation using theSimulation > 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 parametersfor the model solution can also be adjusted (in particular the maximal integration step size and theaccuracy of the integration) using the Simulation > Simulation parameters... menu.

Page 115: manualv2

MATLAB sessions: Laboratory 13 109

Figure L13c: The spring1 model output in the Scope window.

1. Experiment with moving the different blocks in the model by dragging them with the mouse.

2. Experiment with changing the values of the parameters in the different blocks of the spring1model.

3. Why is the integrator block labelled with the symbol 1s? Hint: think of the connection between

the Laplace transforms of y′ and y.

Building a Mass-Spring SIMULINK Model

When building a model from scratch SIMULINK must be started

• from the MATLAB Command Window by entering >> simulink

• by clicking on the SIMULINK button on the MATLAB menu

• by double clicking on the item Simulink > Library browser in the MATLAB Launch Pad win-dow.

The Library Browser window opens, see Figure L13d. A new model can be started from the menu File> New > Model in the Library Browser window. A new window appears. To include blocks in the newwindow simply drag the block needed in the new model from the Library Browser window to the newwindow. Table 3.1 lists the most common blocks used in this lab.

To avoid confusion it is best to approximately position the blocks where we think they will be in thefinal version of the model we are building. Each block should be edited to set the number of input andoutput ports, as well as reasonable values for parameters or ICs. Once this is done connection are madebetween the blocks by simply keeping the mouse down from one output port to the input port of anotherblock. Blocks with no input port are called Sources, and blocks with no output port Sinks. Commentscan be added to the model by double-clicking in the model window and entering the text (which can beedited using the right mouse button).

Page 116: manualv2

110 MATLAB sessions: Laboratory 13

Figure L13d: The SIMULINK Library Browser Window: Windows (left), Unix (right)

Block Name Symbol Library

Integrator Continuous

State-Space Continuous

Fcn Functions & Tables

Gain Math

Product Math

Sum Math

Mux, Demux Signals & Systems

Scope Sinks

XY-Graph Sinks

Constant Source

Sine Wave Source

Table 3.1: Common SIMULINK library block.

Page 117: manualv2

MATLAB sessions: Laboratory 13 111

4. Rebuild the SIMULINK model spring1 (save it as myspring1.mdl). Compare your output in theScope window with Figure L13c). Adjust your model if different.

5. Modify your SIMULINK model to represent the ODE y′′ + y′ + 2y = 1 + sin t.

Alternate SIMULINK Implementations

In general there is no unique way to model a given mathematical problem with SIMULINK. For exampleconsider the differential equation (L13.4). Defining

x =[

yy′

]

we obtaindxdt

=[y′

y′′

]=

[y′

cos t− 4y − y′

]=

[0 1−4 −1

] [yy′

]+

[0

cos t

]= Ax + b (L13.5)

with A =[

0 1−4 −1

]and b =

[0

cos t

]. Equation (L13.5) defines a first-order system. The initial condition

for x is

x(0) =[

y(0)y′(0)

]=

[10

].

Because (L13.5) is first-order a SIMULINK implementation only involves a single integrator . FigureL13e shows a possible implementation. Note the use of the Mux block, which forms the vector b fromits 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′.

Figure L13e: An alternate mass-spring model.

6. Verify that the model shown in Figure L13e implements the problem (L13.5).

7. Build the SIMULINK model as shown in Figure L13e. Compare the output in the Scope windowwith Figure L13c).

Page 118: manualv2

112 MATLAB sessions: Laboratory 13

8. Write the system (L13.5) in the form

dxdt

= Ax + B cos t

y = Cx + D cos t

where A, B, C, and D are 2× 2, 2× 1, 1× 2, and 1× 1 constant matrices, respectively. Then use

a single State-Space block to model the same problem. Your SIMULINK model shouldlook like

9. Figure L13f shows a SIMULINK model.

Figure L13f: A SIMULINK model

Page 119: manualv2

MATLAB sessions: Laboratory 13 113

This model includes three instances of the Fcn function block .

(a) Describe what problem this model solves.

(b) Implement the model and obtain the output from both Scope and XY-graph blocks.

(c) Experiment with other functions in the function blocks .

10. Consider the model shown below.

What IVP is this model simulating? Implement it in SIMULINK and compare the output withthe one obtained by using spring1.mdl.

Page 120: manualv2

114 MATLAB sessions: Laboratory 14

Laboratory 14Laplace 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 functionsnumerically and symbolically (using the MATLAB Symbolic Toolbox). We also show how to use severalMATLAB commands to obtain partial fraction decompositions and solutions of linear IVPs. Our goalis 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

Y (s) =∫ ∞

0

f(t)e−stdt. (L14.1)

The integral in (L14.1)

1. converges at t = 0 if

|f(t)| ≤ C

tρas t → 0 (L14.2)

for some C ≥ 0 and ρ < 1, and

2. converges at ∞ if|f(t)| ≤ Ceσt as t →∞ (L14.3)

for some C ≥ 0 and real σ.

The integral (L14.1) then converges for any s such that <(s) > σ.The Laplace transform is used to solve certain IVPs (in particular linear) essentially because it

transforms ODEs into algebraic equations, which are far easier to deal with.The Laplace transform of a function f can be obtained using the MATLAB Symbolic Toolbox (which

is a front-end to the MAPLE kernel). The following example shows how to obtain the Laplace transformof f(t) = sin(t):

>> syms t % defines t as a symbolic variable>> laplace(sin(t))ans =1/(s^2+1)>> pretty(ans)

1------2

s + 1

Page 121: manualv2

MATLAB sessions: Laboratory 14 115

If the Symbolic Toolbox is not available a numerical approximation of (L14.1) must be computed. Thiscan be done by first transforming (L14.1) using the change of variable u = e−t, i.e., t = − ln u, so that

Y (s) =∫ 1

0

f(− ln u)us−1du. (L14.4)

The following MATLAB function evaluates the integral (L14.4) for a given value of s:

NumLaplace.m

function F = NumLaplace(f,s)tol = 1e-6;warning offif ischar(f), f = inline(f); endF = quadl(@fun,0,1,tol,[],f,s);Fe = quadl(@fun,0,1,100*eps,[],f,s);warning onif 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 routinequadl with target accuracy tol and is compared to a value Fe computed with a higher accuracy. If thetwo 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+1ians =

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 bepredicted by considering the integral (L14.4): for small s the function us−1 is large for u ' 0, in whichcase t = − ln u ' ∞. Since f(t) = sin t oscillates for large t we cannot expect to be able to compute theintegral accurately for small s (and more generally for s with small real part).

Page 122: manualv2

116 MATLAB sessions: Laboratory 14

1. Use NumLaplace to compute a numerical approximation of the Laplace transform of f(t) = sin t fors = 0.1, s = 0.1+10i, s = 10. Compare to the exact values one should get. Which approximationsare 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 SymbolicToolbox 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

transform. For example consider the function f(t) =1− e−t

t√

πt. Note that f ' 1√

πtfor t ' 0 so that

(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 hasno 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 foundas follows. Consider the function g(t) = 1−e−t√

πt.

(a) Use laplace to determine the Laplace transform G(s) of g(t) (if the MATLAB SymbolicToolbox is not available, you can use the fact that the Laplace transform of h(t) = 1√

πtis

H(s) = 1√s, as well as the property that the Laplace transform of e−ath(t) is H(s + a)).

(b) How is f(t) related to g(t)?

(c) How is F (s) related to G(s)? What is F (s)? (if the MATLAB Symbolic Toolbox is available,you can use the symbolic command int if you want).

(d) Evaluate F (1) and compare with the result obtained with NumLaplace above.

Inverse Laplace transform

How do we determine a function f(t) whose Laplace transform F (s) is given? In ODE and Engineeringtextbooks this is normally handled using a table of Laplace transforms that covers various types offunctions F (s) encountered in practice. Functions of the form

F (s) =P (s)Q(s)

e−ct (L14.5)

where P (s) and Q(s) are both polynomials with degree(P )<degree(Q) commonly arise in applications.The term e−ct is indicative of a delay in the inverse transform f(t) (recall that the Laplace transform ofH(t − c)f(t − c) is F (s)e−ct). The fraction P (s)

Q(s) can always be decomposed into partial fractions thatappear in tables.

The function InvLaplace automates the partial fraction decomposition and the inverse transformfor this class of functions F (s):

Page 123: manualv2

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 = P1; q = Q1;for i=2:m, p = conv(p,Pi); endfor j=2:n, q = conv(q,Qj); 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)]; endfa = zeros(size(d));for j=1:length(d), fa(j) = factorial(d(j)); endd = 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);

elsedisp(’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 int. It does not return an algebraic expression for f(t). The two standard MATLAB functions conv andresidue 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 transformof F (s) = (2s+1)(s+3)

5s3+2s2+3s+1e−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’)

Page 124: manualv2

118 MATLAB sessions: Laboratory 14

(2s+1)(s+3)--------------5s^3+2s^2+3s+1

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

0 20 40 60 80 100 120−1.5

−1

−0.5

0

0.5

1

1.5

2

t

f(t)

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

F The MATLAB Symbolic Toolbox function ilaplace determines the inverse transform using symbolicoperations. For example

>> syms s>> f = ilaplace(1/(s^2+1))f =sin(t)>> ezplot(f,[0,120]) % to plot symbolic functions

For the function F (s) = (2s+1)(s+3)5s3+2s2+3s+1e−10s we obtain

>> syms s>> ilaplace(exp(-10*s)*(2*s+1)*(s+3)/(5*s^3+2*s^2+3*s+1))ans =2*Heaviside(t-10)*sum((-30/671*_alpha^2+35/671*_alpha+39/671)*exp(_alpha*(t-10)),_alpha = RootOf(5*_Z^3+2*_Z^2+3*_Z+1))+7*Heaviside(t-10)*sum((-108/671*_alpha-195/671*_alpha^2-82/671)*exp(_alpha*(t-10)),_alpha = RootOf(5*_Z^3+2*_Z^2+3*_Z+1))+3*Heaviside(t-10)*sum((138/671-31/671*_alpha+410/671*_alpha^2)*exp(_alpha*(t-10)),_alpha = RootOf(5*_Z^3+2*_Z^2+3*_Z+1))

Page 125: manualv2

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 Toolboxfunction 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 integralformula. This formula is generally not mentioned in textbooks because it is not trivial to apply it evento simple Laplace transforms such as F (s) = 1

s , let alone to more complex functions. It is sufficient hereto remark that this formula requires the knowledge of F (s) for complex values s and not simply for realvalues (i.e., a plot of F (s) for s real is not sufficient to get an idea of f(t)!). Numerical evaluation of theintegral 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) iscalled invlap.m and can be found at www.mathtools.net/Basic/Mathematics/MATLAB/. We use it toobtain the inverse transform for the problem of Figure L14a:

t = .1:.1:120;f = invlap(@F,t,0);plot(t,f); grid on; xlabel(’t’); ylabel(’f(t)’);%------------------------------------------------------function Fv = F(s)Fv = exp(-10*s).*(2*s+1).*(s+3)./(5*s.^3+2*s.^2+3*s+1);

0 20 40 60 80 100 120−1.5

−1

−0.5

0

0.5

1

1.5

2

t

f(t)

Figure L14b: Numerical inverse Laplace transform of F (s) = (2s+1)(s+3)5s3+2s2+3s+1e−10s using invlap.

The inverse transform in Figure L14b is identical to that in Figure L14a up to time t ' 85. For large t(i.e., for small s) the result returned by invlap is totally inaccurate and cannot be used to determinethe long time behavior of f(t). How large can t be? This depends on the function F (s). In generalfunctions 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

Page 126: manualv2

120 MATLAB sessions: Laboratory 14

t = 10. Does the function exhibit a discontinuity at t = 10? What is the size of the jump? Canyou 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.

(a) F (s) =1

(s + 1)(s + 2)

(b) F (s) =1

s2 + 1

(c) F (s) =e−5t

(s + 0.1)(s2 + 0.01)

(d) F (s) =1s5

(e) F (s) =e−s

s + 1+

e−2s

s + 2

(f) F (s) =1

(s + 1)(1 + e−s)

(g) F (s) = ln(

1 +1s2

)

(h) F (s) =1s2− 1

s(es − 1)

Inverse Laplace transform using SIMULINK

We introduced SIMULINK in Laboratory 13. Here we build a simple model to obtain a graph of theinverse transform of functions F (s) of the form (L14.5) using the Transfer Function block andthe Step Function block . The example of the function F (s) = 2s2+5s+3

5s3+2s2+3s+1e−10s is shown in FigureL14c.

Figure L14c: SIMULINK model for the Laplace transform inversion.

To understand why the transfer function appearing in the Transfer function block is2s3 + 5s2 + 3s

5s3 + 2s2 + 3s + 1

and not2s2 + 5s + 3

5s3 + 2s2 + 3s + 1recall that the Laplace transform of the Heaviside (step) function H(t− c)

is H(s) = e−cs

s . The model then outputs (on the Scope) the inverse transform of

2s3 + 5s2 + 3s

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

s=

2s2 + 5s + 35s3 + 2s2 + 3s + 1

e−10s = F (s).

The output shown Figure L14d is obtained by double-clicking on the Scope (some of the parameterssuch as the final simulation time can be changed using the Simulation > Simulation Parameters...menu).

Page 127: manualv2

MATLAB sessions: Laboratory 14 121

Figure L14d: Output for the SIMULINK model of Figure L14c.

F A factor of the form 11−e−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 theinverse transform of the resulting function for 0 < t ≤ c. For example consider the function

F (s) =1

s(1 + e−s)=

1− e−s

s(1 + e−s)(1− e−s)= G(s)× 1

1− e−2swith G(s) =

1− e−s

s.

The function f(t) is then the 2-periodic prolongation of the function g(t) which is the inverse transformof G(s) computed on the interval 0 < t ≤ 2. Using InvLaplace we obtain

>> t=0:.1:2;>> f=InvLaplace([1],[1,0],0,t) ...

-InvLaplace([1],[1,0],1,t);>> plot(t,f)

0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 20

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

1

while using invlap yields

Page 128: manualv2

122 MATLAB sessions: Laboratory 14

function testt=.1:.1:2;f=invlap(@F,t,0);plot(t,f)%----------------function Fv = F(s)Fv = (1-exp(-s))./s;

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

0

0.2

0.4

0.6

0.8

1

1.2

6. Comment on the differences between the output of the two graphs. What happens when usingmore points in t? How can the function f(t) be plotted on the interval [0, 4]? On any interval?

7. Determine the inverse transform of the following functions

(a) F (s) =20(1− e−πs)

s(s2 + 4s + 20)(1 + e−πs)(b) F (s) =

1s(1 + e−s)(1 + e−2s)

Application to the solution of initial value problems

We now apply the functions NumLaplace, InvLaplace, and invlap to the solution of linear initial valueproblems of the form

c1y(n) + c2y

(n−1) + · · ·+ cny′ + cn+1y = f(t) with y(0) = y0, . . . , y(n−1)(0) = y

(n−1)0 given. (L14.6)

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

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

of the solutions of the homogeneous problem

c1y(n)h + c2y

(n−1)h + · · ·+ cny′h + cn+1yh = 0 with yh(0) = y0, . . . , y

(n−1)h (0) = y

(n−1)0 given, (L14.7)

and the forced problem with 0 initial conditions

c1y(n)f + c2y

(n−1)f + · · ·+ cny′f + cn+1yf = f(t) with y(0) = 0, . . . , y(n−1)(0) = 0. (L14.8)

The Laplace transform of y is

Y (s) = Yh(s) + Yf (s) =P (s)Q(s)

+F (s)Q(s)

(L14.9)

with Q(s) = c1sn + c2s

n−1 + · · · + cns + cn+1. The polynomial P (s) depends on the initial conditionsy0, . . . , y

(n−1)0 . If y0 = . . . = y

(n−1)0 = 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 samplepoints t. The following example illustrates how the solution of the IVP y′′ + 4y = sin t with y(0) = 1,y′(0) = 0, is obtained:

Lab14.m

function Lab14% Solution of the IVP y’’+4y = sin(t) with y(0)=1, y’(0)=0% using Laplace transforms; assumes Laplace transform of forcing term is given

Page 129: manualv2

MATLAB sessions: Laboratory 14 123

c = [1,0,4]; IC = [1,0]; % ODE coefs and ICst = .1:.1:20;[P,Q] = free_response(c,IC);disp(’Laplace transform of y_h =’); nice(P,Q,’s’)FP = [1]; FQ = [1,0,1];disp(’Laplace transform of f(t) =’); nice(FP,FQ,’s’)YP = FP; YQ = cellprod(FQ,Q);disp(’Laplace transform of y_f =’); nice(YP,YQ,’s’)

y_h = InvLaplace(P,Q,0,t);y_f = InvLaplace(YP,YQ,0,t);y = y_h+y_f;plot(t,y_h,’k+-’,t,y_f,’b-’,t,y,’ro-’,’MarkerSize’,5)legend(’free response (forcing = 0)’,’response of forcing (IC = 0)’,’total response’)

The function free response determines the polynomials P and Q in Yh(s). The Laplace transformof f(t) = sin t is F (s) = FP (s)

FQ(s) where FP and FQ are given polynomials. Here FP (s) = 1 and

FQ(s) = s2 + 1. As a result the second fraction in (L14.9) can be written F (s)Q(s) = FP (s)

FQ(s)Q(s) . Thefunction cellprod then determines the product FQ(s)Q(s) as a single polynomial in the appropriateformat suitable for use in InvLaplace.

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

−1

−0.5

0

0.5

1

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

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

F If F (s) is unknown it must be computed numerically using NumLaplace. The inverse Laplacetransform of F (s)

Q(s) must then also be determined numerically using invlap. Because invlap requires for

each value of t the evaluation of F (s)Q(s) at many (complex) s values this is a very expensive task:

Lab14b.m

function Lab14b

Page 130: manualv2

124 MATLAB sessions: Laboratory 14

% Solution of the IVP% y’’+4y = sin(t) with y(0)=1, y’(0)=0% using numerical Laplace transforms

global Q

c = [1,0,4]; IC = [1,0];t = .1:.1:20;[P,Q] = free_response(c,IC);disp(’Laplace transform of y_free =’); nice(P,Q,’s’)

y_h = InvLaplace(P,Q,0,t);y_f = invlap(@F,t,0);y = y_h+y_f;plot(t,y_h,’k+-’,t,y_f,’b-’,t,y,’ro-’,’MarkerSize’,5)legend(’free response (forcing = 0)’,’response of forcing (IC = 0)’,’total response’)

%------------------------------------------------------------------------------------function Fv = F(s)global QFv = zeros(size(s));for i = 1:length(s)

Fv(i) = NumLaplace(@forcing,s(i));endFv = Fv./polyval(Q1,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 arenot used numerically in practice and essentially require the use of a table or a set of rules to symbolicallydetermine 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 followingIVPs.

(a) y′′′′ + 5y′′ + 4y = 0 with y(0) = 1, y′(0) = 0, y′′(0) = −4, y′′′(0) = 1.

(b) y′′ + ay′ + y = sin t with y(0) = 1, y′(0) = 0 for a = 5, 2, 1, 0.1.

(c) y′′ + 4y =

sin t for t < π2

1 for t ≥ 1 with y(0) = 1, y′(0) = 0.

(d) y′′ + y =mod(floor(t),2) with y(0) = 1, y′(0) = 0.

Page 131: manualv2

MATLAB sessions: Laboratory 14 125

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

−1

−0.5

0

0.5

1

1.5

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

Figure L14f: Solution of the IVP y′′ + 4y = sin t, y(0) = 1, y′(0) = 0 using NumLaplace andInvLaplace/invlap with homogeneous and forced contributions.

Page 132: manualv2

126 MATLAB sessions: Laboratory 14

Page 133: manualv2

Chapter 4

Additional Project Descriptions

Note to the Instructor: Group Projects

One of the strengths of the Nagle, Saff and Snider text is the number of projects that are included atthe end of each chapter. The selection of projects is expanded in the new edition (6th ed., 2004) as itincludes a number of projects contributed by instructors who have used previous editions of the book.MATLAB and SIMULINK can be used to assist with these projects in many ways.

The additional projects presented in this supplement illustrate that a project can be designed aroundalmost any topic. These projects represent a diverse set of applications, including chemical engineering,mathematical epidemiology, special functions, electrical circuits, athletics, and an area where such ODEtechniques have been rarely applied - the dynamics of love. Likewise, the analytical tools required tocomplete the investigation of the projects are varied. One of the models emphasizes the modellingprocess more than the solution of the IVPs, and many of them involve systems of ODEs.

A brief overview of each project contained in this section is provided below. The actual descriptioncomprises the remainder of this chapter (there is no specific ordering to the projects).

• Design Your Own ProjectThe basic idea is for each (team of) student(s) to find an application of differential equationsrelated to a topic of personal interest - their major, another course in which they are currentlyenrolled, or something that fascinates them - and prepare a project description, complete with aderivation of a model, questions to be addressed, and realistic data. After the project descriptionis approved students have to prepare a project report.

• The ODE of World-Class SprintThis project is ideal for use with Chapter 2 of Nagle, Saff & Snider. The differential equationis linear (and separable). The real interest in this project is the mathematical modelling. Theapplication is easy to understand and discuss. The questions are not technically sophisticated,but some of the underlying assumptions and interpretations are not completely trivial. Familiaritywith least-squares techniques is helpful, but not necessary, in Step III of the project.

• Consecutive Reactions for Batch ReactorsThis is another project that can be given very early in the semester. Even though the mathematicalmodel is a system of linear ODEs, the system is “lower triangular” and can be solved by “forwardsubstitution”.

The specific constants used in this lab do not pertain to any real situations. It’s not unreasonableto ask the students to research this problem and identify specific instances in which this modelarises as well as realistic parameter values.

This project originated from Ralph White, Chemical Engineering and Center for ElectrochemicalEngineering, University of South Carolina, as part of a project funded by the Lilly Foundation andthe USC Office of the Provost.

127

Page 134: manualv2

128 Additional Project Descriptions

• Normal T-CellsThis project is Part I of a two-part problem. The second part (“T-cells in the presence of HIV”) isappropriate only after systems of ODEs have been discussed. This project requires only the basicsof 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 HIVThis project is Part II of a two-part problem. The first part (“Normal T-cells”) can be assignedmuch 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 forHIV/AIDS. An accessible discussion of this topic can be found in the paper Using Mathematicsto understand HIV immune dynamics by Denise Kirschner (Notices of the AMS 43(2) (February1996) 191-202).

• Design of an Electrical NetworkThis lab is based on a standard problem in electrical circuits. The focus is on the parametricanalysis 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 thevalue of this resistance.

This project requires knowledge about systems of linear ODEs. While it is ideally suited forsolution using matrix methods (Ch. 9), the project can be modified (see next comment) so that itis 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 andSnider. Also, there are two values of the resistance for which the system does not have a full setof 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 LoveThis project is based on a differential equations model developed by S. Rinaldi describing thedynamics 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 expectto apply the knowledge they gained in the course to purely Engineering fields.

• Hypergeometric FunctionsA nice introduction to hypergeometric functions is presented in §8.8, page 484, of Nagle, Saff andSnider. This project expands on the multitude of identities involving these functions.

Page 135: manualv2

Additional Project Descriptions 129

P1. Design your Own Project

Step I: Identify the Application

A variety of applications of differential equations are discussed in the text and in this laboratory manual,including Newtonian mechanics, population dynamics, electrical circuits, and mixing problems. The di-versity of these applications illustrates the broad applicability of differential equations. To add emphasisto this point, this project requires that you identify an application of differential equations in a subjectarea of particular interest to you.

You are specifically encouraged to discuss this project with a project mentor. This mentor shouldbe a professional scientist, e.g., a professor for another course you are presently taking or plan to take.Provide a copy of this project assignment.

The application should be solvable by techniques discussed in this course. The only other requirementis that the model have at least one parameter. The problem might involve a single higher-order or asystem of ordinary differential equations, with appropriate initial values.

Step II: Background Investigation

The main result of this assignment will be a brief description of your project in the form of a projectassignment. Prior to writing this assignment, it will be necessary for you to thoroughly understand theproblem and the main questions that are to be addressed.

In consultation with your project mentor, you should identify a short list of references for yourapplication. These references should be accessible to students in your class, but they do not need to bemathematical.

Study these references and pay special attention to the mathematical modelling used to convert thephysical problem into a mathematical problem, any assumptions that are made during the modellingprocess, and the questions that will be the focus of the project description you will create (be sure torequest assistance and clarifications from your mentor or differential equations instructor, as needed).

Step III: Project Description

Prepare a project description for your project. This description should be no longer than two pages,must be typed (including equations if any) and may include illustrations or other graphics as needed.

The project description should contain all of the following: title, your name/team members, the nameof your project mentor, a brief description of the physical problem, a summary of the mathematicalmodelling, questions to be answered in the analysis, realistic values for all parameters, and referencesrelated to the project.

Step IV: Summary and Conclusions

This project is longer than it sounds, unless you start early and divide the assignment into manageableportions. It is important that you select relevant, interesting, and tractable questions. This may requirea few iterations before you find the appropriate level. You may need to discuss your ideas with yourinstructor and ask for help when needed.

In the end be sure that all questions are answered and that the final report is similar in style to theother project reports prepared for this course.

Page 136: manualv2

130 Additional Project Descriptions

P2. The ODE of World-Class Sprint

Understanding the Model

According to Keller’s theory of competitive running, published in 1973, track sprints of up to 300 meterscan be described by the differential equation

dv

dt= A− v

τ.

At the time of this analysis, the best constants were A = 12.2 m/s and τ = 0.892 s.

1. What is an appropriate initial condition for this problem?

2. In your own words, explain each of the terms in the differential equation and how the terms combineto form a complete model. What is an interpretation of the two parameters A and τ? Does thedifferential equation seem reasonable in your experience? Do you know any other situation thatcould be described using this same model?

Finding and Interpreting Solutions

One reason for solving differential equations is to derive further consequences from the solution. Thenext set of questions explores the solution and its consequences.

3. Solve the IVP for v = v(t) numerically using ode45.m or euler.m.

4. Determine numerically the distance d = d(t) travelled as a function of t (use trapz.m or quadl.m,or solve another IVP satisfied by d).

5. Find the acceleration a = a(t) function by differentiating v numerically (use the diff function).Also, write a differential equation satisfied by a. What is the initial condition? Solve directly thisdifferential 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 the1973 parameters. When does the maximum acceleration occur? How long does it take for theacceleration 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 thismaximum? Compare the final speeds in a 100 meter and a 200 meter race. Explain your findings.

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

Extending the Problem (Parameter Estimation)

Another aspect of differential equations is to use the solution to estimate the parameters of the problem.This is a form of inverse problem, a sometimes difficult problem and active research area in appliedmathematics.

Race officials often record the split times of runners in addition to final times. Split times are themeasure of time required to cover portions of the distance. Table 1 lists the results for the top four menand women in the 100 meter final at the 1993 World Track and Field Championships held in Stuttgart,Germany.

9. Plot the data points on the same plot as the d curve obtained using the 1973 parameters. Doesthe curve fit the data points?

10. Determine values for the parameters A and τ based on the data from the Table (use the MATLABfunction fminsearch, see Lab 5 page 64)

Page 137: manualv2

Additional Project Descriptions 131

Name Sex Nation 30m 60m 80m 100mLinford Christie M GRB 3.85 6.45 8.15 9.87Andre Cason M USA 3.83 6.43 8.15 9.92Dennis Mitchell M USA 3.82 6.46 8.22 9.99Carl Lewis M USA 3.95 6.59 8.30 10.02Gail Devers W USA 4.09 6.95 8.86 10.82Merlene Ottey W GHA 4.13 6.98 8.87 10.82Gwen Torrence W USA 4.14 7.00 8.92 10.89Irina Privalova W RUS 4.09 7.00 8.96 10.96

Table 1: Split times (in seconds) for 100m sprint, 1993 World Track and Field Championships.Courtesy of Shawn Price of Track and Field News

Summary and Conclusions

The theoretical analysis and the work that you have done with the data should give you a better insightinto this model. To conclude the project, let’s consider a few of the following points.

11. Is it preferable to accelerate quickly at the start and then maintain the speed or to hold backand accelerate gradually? How would the model change to allow for weakening, i.e., deceleration,towards the end of the race?

12. Are the results produced by the model reasonable? Why does Keller suggest that this model isvalid only for races up to 300 meters? do you agree with this? What types of modifications wouldbe 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.

Page 138: manualv2

132 Additional Project Descriptions

P3. Consecutive Reactions for Batch Reactors

Understanding the Model

Consider first-order reactions involving three substances, A, R, and S, which are carried out isothermallyin either the gas or liquid phase in a perfectly mixed batch reactor. The reaction begins with a puresample of component A. The process can be schematically represented as

Ak1−→ R

k2−→ S

where k1 is the reaction rate for the conversion of A into R and k2 represents the reaction rate for theconversion of R into S.

The primary objective is to determine the amount of each substance in the reactor as a functionof time after the reactor starts. Additional information that is desired includes the time at which thesubstance 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 tothe amount present in the reactor.

1. Write a mathematical model describing the evolution of all three concentrations over time. Yourmodel should contain three differential equations with appropriate initial conditions. For examplethe equation describing changes in [R] reads

d[R]dt

= k1[A]− k2[R]

(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 thesection ”Understanding the model”.

Solution and Analysis

3. Simulate numerically the solution of your system in the cases

(a) k1 = 1, k2 = 3,

(b) k1 = 3, k2 = 1,

(c) k1 = k2 = 2.

4. Use the ideas from first-order linear equations to find analytic solutions for [A], [R], and [S]. Besure to find solutions for all possible combinations of k1 and k2 (both positive).

Summary and Extensions

Use your findings to provide complete answers to the questions posed at the end of the first section forany positive constants k1 and k2. How is the model modified if one assumes that the first reaction is

now reversible in the form Ak1−→←−k3

R? What if the reaction is second-order?

Bibliography

[1] Holland, C. D. and Anthony, R. G., Fundamentals of Chemical Reaction Engineering, Prentice-Hall(1979).

Page 139: manualv2

Additional Project Descriptions 133

P4. Normal T-Cells

Background

In [3] Perelson, Kerschner, and DeBoer present a model for the interaction of T-cells and HIV. In thisproject we examine a preliminary model which explains the normal functioning of T-cells. The modelof T-cell formation in the presence of HIV is discussed in the project “T-cells in the Presence of HIV”.

The general goal of this project is to explain a biological theory. Throughout the investigationmathematical problems are encountered, formulated, solved, and interpreted. An even more informativeview can be obtained by comparing this discussion with the original one in [3].

Basic Model

T-cells are a natural and essential component of the human immune system. The primary job of T-cells is to attack and destroy cancerous cells, cells infected with a virus, and, in general, any cellcontaining foreign antigens. Prior to examining the interaction between T-cells and HIV, it is necessaryto 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 arecreated in the lymphatic tissues (including the thymus). These tissues normally produce T-cells at auniform (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 indays) must account for the two different mechanisms controlling the production of T-cells and the deathof T-cells as they age. Assuming a logistic growth model for the need-based production of T-cells, anda constant per-capita death rate µ, this model takes the form

dT

dt= s + rT

(1− T

Tmax

)− µT = f(T ).

The parameters s, r, Tmax, and µ are all positive. Note that this model does not take into account thedeath of T-cells due to the presence of the virus, simply the natural propensity of T-cells to respond tothe attack by the virus.

Understanding the Basic Model

1. What are the units associated with each of the parameters?

2. Explain why the conditions f(0) > 0 and f(Tmax) > 0 assure that the number of T-cells will staybetween 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 IntermediateValue Theorem, that there is some value T ∗ for which f(T ∗) = 0. What is the significance of T ∗?Determine T ∗ explicitly in terms of s, r, Tmax, and µ. Identify two parameters (functions of s, r,Tmax, and µ) the ratio T ∗/Tmax depends on.

Qualitative Analysis for a Specific Case

Realistic values of the parameters are s = 10, r = 0.03, Tmax = 1700, and µ = 0.02.

4. Do these values satisfy the constraints identify earlier? Numerically determine the value T ∗ (e.g.,obtained after t = 100 using ode45)? Is this consistent with the biological descriptions and theanalytic result?

5. Determine the behavior of solutions for initial conditions between 0 and Tmax. Do all solutionsstay in the desired interval?

Page 140: manualv2

134 Additional Project Descriptions

Qualitative Analysis for the General Case

We now investigate the behavior ofT ∗

Tmaxas a function of α =

µ

rand β =

s

rTmax.

6. Select a grid of point in the (α, β) domain around the point corresponding to the specific caseabove. For each point in the grid numerically compute an approximation to T ∗. Plot the resultsusing a surface plot (surf). Compare with the analytic expression obtained earlier.

7. Draw conclusions regarding the level of T ∗ in terms of the parameters. Is this what you expected?

8. (optional) Create a SIMULINK model for this problem.

Bibliography

[1] Greene, W. C., AIDS and the Immune System, Scientific American (Sept. 1993, Special Issue).

[2] Herod, J. V., A Model for an HIV Infection, Maple Technical Newsletter 10 (1993) 72-78.

[3] Perelson, A.S., Kerschner, D. E. and Deboer, R., Dynamics of HIV Infections of CD4+ T-cells,Mathematical Biosciences 114 (1993) 81-125.

Page 141: manualv2

Additional Project Descriptions 135

P5. T-Cells in the Presence of HIV

Background

In [3] Perelson, Kerschner, and DeBoer present a model for the interaction of T-cells and HIV. In theproject “Normal T-cells” we learned how T-cells function in a healthy individual. In this project wediscuss some of the changes needed to adapt the model in the presence of HIV in the body. Thisdiscussion is more difficult than in the previous project. Thinking about the biological interpretation ofeach term should help you understand the model. The final qualitative results should be consistent withwhat you know about T-cells, HIV and AIDS.

The general idea of this project is to explain a biological theory. Throughout the investigationmathematical problems are encountered, formulated, solved, and interpreted. An even more informativeview can be obtained by comparing this discussion with the original one in [3]. You may also want toread first, without necessarily investigating, the project “Normal T-cells”.

The Model

When attacked by the HIV virus T-cells are able to fight off the invasion for a period of time, buteventually must give up to the onslaught. As a result, the immune system becomes less effective atfighting diseases (including the spread of HIV). The models presented in this section incorporate someof 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 thevirus) or active (i.e., spread the virus). Therefore the new model must describe the evolution of fourdifferent populations: the size V of the HIV population, the number T of healthy T-cells, the numberTL of latently infected T-cells, and the number TA of actively infected T-cells. A different differentialequation is needed for each of T , TL, TA, and V . The complete model of four differential equations isassembled by considering each population separately.

• Normal T-cells are produced and die according to processes identified in the earlier project. Inaddition, interactions between healthy T-cells and the virus transfer some normal T-cells intolatently infected T-cells. The rate of change of healthy T-cells is then given by

dT

dt= s + rT

(1− T + TL + TA

Tmax

)− µT − k1V T = fT (T, TL, TA, V ).

• The infected T-cells population increases as normal T-cells interact with the virus and decreasesdue to both natural death and transfer to actively infected T-cells. The differential equationdescribing the rate of change of TL thus reads

dTL

dt= k1V T − µTL − k2TL = fTL(T, TL, TA, V ).

• The actively infected T-cells population grows due to conversion of latently infected T-cells anddecreases due to viral replication. A model for the rate of change of actively infected T-cells isthen

dTA

dt= k2TL − bTA = fTA

(T, TL, TA, V ).

• Finally the viral population is assumed to grow at a rate proportional to the death rate of activelyinfected T-cells (with constant of proportionality N). The only ways in which free virus is removedis by combination with healthy T-cells or by clearance from the body (e.g. through transfusion).The equation for the rate of change in the virus population is thus given by

dV

dt= NbTA − k1V T − aV = fV (T, TL, TA, V ).

Page 142: manualv2

136 Additional Project Descriptions

Understanding the Parameters and Checking the Model

1. Assuming that each population is measured in cells per cubic millimeter and time is measured indays, determine the units associated with each of the parameters.

2. The model remains appropriate as long as each population does not become negative. Startingwith 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 dT

dt = s > 0, guaranteing that T > 0 for all t. Determineconditions 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 infectionevolve 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 conditionsV (0) = 10−3 over the interval 0 ≤ t ≤ 150. Create one plot showing TL, TA, and V . Create aseparate plot showing the evolution of the healthy T-cells. Why is this population not included inthe other plot?

4. Note the dramatic initial increase in the (free) virus population. Which term in the equation forV 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 Tat 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) = 0instead? When does the healthy T-cell count first drop below the normal range for a healthyindividual? How much longer does it take for the solution to converge to a steady-state solution?Is is likely that this transition will occur during the patient’s lifetime?

7. Experiment with a range of values for N . Does the infected steady-state always exist?

8. (optional) Create a SIMULINK model for this model.

Concluding Remarks and Extensions

The model developed in this problem is consistent with the current understanding of the transition frominfection with HIV to the onset of AIDS. That is, immediately after infection there is an enhancedlevel of infected T-cells. After only a few days these levels become so low they are undetectable usingtypical testing procedures. During this period the normal T-cell population is strong enough to combatthe virus. However, the level of T-cell production cannot be maintained forever. At some point AIDSbecomes detectable as the T-cell concentration drops to a fraction of the necessary level.

While the overall picture presented by this model is rather bleak, there are some bright spots. Inparticular, this model suggests that the onset of AIDS can be delayed if healthy T-cell production canbe extended. This is the idea behind some of the drugs already being tested and used for the “treatment” of AIDS.

NOTE added: A simplified model combining both latent and actively infected populations into asingle infected state I is also included in [4]. An interesting exercise would be to compare the twomodels and test the validity of the simpler model as a suitable reduction of the model used here. Modelreduction is an important aspect of the modelling process because it makes the problem mathematicallymore tractable and generally provides additional insight into the fundamental properties of the originalproblem.

Page 143: manualv2

Additional Project Descriptions 137

Bibliography

[1] Greene, W. C., AIDS and the Immune System, Scientific American (Sept. 1993, Special Issue).

[2] Herod, J. V., A Model for an HIV Infection, Maple Technical Newsletter 10 (1993) 72-78.

[3] Perelson, A.S., Kerschner, D. E. and Deboer, R., Dynamics of HIV Infections of CD4+ T-cells,Mathematical Biosciences 114 (1993) 81-125.

[3] Culshaw, R. V. and Ruan, S, A delay-differential equation model of HIV infection of CD4+ T-cells,Mathematical Biosciences 165 (2000) 27-39.

Page 144: manualv2

138 Additional Project Descriptions

P6. Design of an Electrical Network

Understanding the Problem

The objective of this project is to design an electrical network to meet specific design criteria. Thenetwork consists of two loops, see Figure 1. The left loop contains a E = 12 Volt emf and a L = 1 Henryinductor. The right loop contains a C = 1

4 Farad capacitor and a R = 6 Ohm resistor. A resistor withunspecified resistance r is on the common side of both loops. There is no current in the network until aswitch, located in the left loop, is closed.

AA¢¢AA¢¢AA

©©HH©©HH©©

r

E R

r

LC

Figure 1: 2-loop network

The objectives are to determine steady-state currents (as functions of the resistance r), identify thedifferent qualitative behaviors of the transient currents, and investigate the length of time required forthe 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 differentialequations 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/dtdI2/dt

]= A

[I1

I2

]+ b

where A is a 2× 2 matrix and b a 2-dimensional vector both depending on r. What are the initialconditions?

2. How are the equations changed if the first loop contains also a 12 Farad capacitor.

Solution and Analysis

3. Determine the steady state solution as a function of the resistance r, both algebraically and nu-merically.

4. Plot the two eigenvalues of A in the complex plane as r varies. For what values of r do solutionsoscillate?

5. Determine as a function of r the amount of time required to ensure that the current in each loopis within 10% of the steady-state value.

6. The network is rated to support a maximum current of Imax = 3 Amperes. What resistance r willguarantee that the current in the network never exceeds this limit?

Page 145: manualv2

Additional Project Descriptions 139

Summary and Conclusion

The network considered here is not very sophisticated. While the problem would involve more variablesand the manipulations would be more difficult for more complicated networks, the same analytical andnumerical tools can be used to determine answers to the same set of questions.

Page 146: manualv2

140 Additional Project Descriptions

P7. The Dynamics of Love

Background

Francesco Petrarca (also known as Petrarch) was a scholar and poet in 14th century Italy who fell in lovewith Laura, a beautiful but married lady of Avignon, France, when he was 23. Over the next 21 yearsPetrarch would write a collection of 366 poems in her honor, eventually published as the Canzoniere.These poems express a wide range of emotions, from extreme elation to deep despair. However the timeline of when these poems were written is unclear and scholars have expanded considerable effort over theyears trying to bring some temporal order into this work. In [1] S. Rinaldi developed a relatively simpledifferential equation model expressing the emotions of Petrarch and Laura, recreating a chronology forthe various poems.

In this project we focus on two aspects of this model. The first goal is to replicate the results obtainedin [1]. The second phase explores changes in the outcome of the model when parameters are changed,in particular regarding the existence of a steady-state.

Understanding the Model

Laura is described by a single variable L(t) representing her attitude towards Petrarch. Positive valuesindicate sympathy and affection while negative values mean coldness and antagonism. Petrarch, onthe other hand, is described by two variables: his love P (t) for Laura, and his poetic inspiration I(t).High values of P correspond to ecstatic love, while low (negative) values indicate despair. The modeldeveloped by Rinaldi reads:

dL

dt= −α1L + β1

[P

(1− P 2

)+ AP

],

dP

dt= −α2P + β2

[L +

AL

1 + Z

],

dI

dt= −α3I + β3P.

The parameters αi and βi, i = 1, 2, 3 are positive numbers. The quantities AP and AL describe thephysical appearance of Petrarch and Laura. Admittedly AP < 0 while AL >> 0.

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

2. Explain in plain English the contribution of the different terms in the equations and their effecton the rate of change of the variables L, P , and I.

Simulation and Perturbation

Rinaldi estimated parameter values based on his own interpretation of selected poems and a calibrationwith recent literary studies, and obtained the following values (with t measured in years):

α1 = 3.6, α2 = 1.2, α3 = 0.12, β1 = 1.2, β2 = 6, β3 = 12, AL = 2, AP = −1.

3. What are suitable initial conditions for P (0) and L(0)? Knowing that Petrarch wrote his firstpoem 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 Land 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 beingfixed)? Experiment with varying other parameters to obtain a similar behavior (hint: α’s must beincreased, β’s decreased, and physical appearances AP and AL get closer to 0, i.e., neutral). Whatdo you think is the most sensitive parameter in the model?

Page 147: manualv2

Additional Project Descriptions 141

We now keep the ratio β3/α3 and all other coefficients constant at their level used above and want toestimate 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 periodsensitive 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 thecase of Petrarch and Laura, it provides a fairly accurate match for data obtained independently throughliterary analysis.

Bibliography

[1] S. Rinaldi, Laura and Petrarch: an intriguing case of cyclical love dynamics, SIAM Journal onApplied 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.

Page 148: manualv2

142 Additional Project Descriptions

P8. Hypergeometric Functions

The hypergeometric differential equation is the linear second-order ODE

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

with parameters α, β, and γ. For γ 6= 0,−1,−2, . . . the method of Frobenius yields a solution to thisequation as a power series

y(x) = 1 +αβ

γx +

∞∑n=2

(α)n(β)n

n!(γ)nxn = F (α, β, γ; x) (2)

where (a)n = (a + n− 1) · · · (a + 1) for n = 2, 3, . . . This function is called hypergeometric function.The interest in such functions is that mostly any linear homogeneous second-order ordinary differen-

tial equations can be transformed into the hypergeometric differential equation. A number of propertiesof hypergeometric functions were established in §8.8 of the Nagle/Saff/Snider text. In this project wepropose to verify numerically and, in some instances algebraically, some of these identities, as well asevaluate the convergence of the series (2).

Basic Identities

1. What are the initial conditions satisfied by F (α, β, γ; x)?

2. Prove the identity F (1, 1, 1; x) = 11−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 numericalintegration using odeset). Test your routine by checking the following identities

(a) F (1, 1, 1; 12 ) = 2,

(b) F ( 13 , 2

3 , 56 ; 27

32 ) = 85 ,

(c) F ( 13 , 2

3 , 56 ; 27

32 ) = 85 .

Hypergeometric and Elementary Functions

4. Prove or disprove, numerically and/or analytically, the following identities. Specify the domain ofvalidity of the identities.

(a) F ( 12 ,− 1

2 , 12 ; sin2 x) = cos x,

(b) F ( 12 , 1

2 , 32 ;x2) = arcsin x

x ,

(c) F ( 12 , 1, 3

2 ;−x2) = arctan xx ,

(d) F (1, 1, 2;−x) = ln(1+x)x ,

Hypergeometric Functions and Differential Equations

5. Prove that the identityd

dxF (α, β, γ;x) =

αβ

γF (α + 1, β + 1, γ + 1; x) holds for −1 < x < 1

(a) analytically by differentiating the series (2) termwise.

(b) analytically by showing thatd

dxF (α, β, γ; x) satisfies an appropriate differential equation with

suitable initial conditions.

(c) numerically by comparing the direct evaluation of F (α, β, γ;x) via hypergeom.m with αβγ

∫ x

0F (α+

1, β + 1, γ + 1; t) dt.

Page 149: manualv2

Additional Project Descriptions 143

6. Set α = β = 1 and γ = 12 . The hypergeometric function F (1, 1, 1

2 ; x) then satisfies the ODE (1).Show algebraically or numerically that

√xF ( 3

2 , 32 , 3

2 ;x) is a linearly independent solution to (1) for0 < x < 1.

Hypergeometric Functions and Polynomials

7. For what values of α and/or β is F (α, β, γ; x) a polynomial?

8. Show the identity F (−m + 1, 1, 2; x) = 1−(1−x)−m

mx .

Bibliography

[1] Abramowitz, M. and Stegun, I. A. (eds.), Handbook of Mathematical Functions with Formulas,Graphs and Mathematical Tables, Dover, 1972, pp. 555-566.

[2] Zucker, I. J. and Joyce, G. S. Special Values of the Hypergeometric Series II., Math. Proc. Cam-bridge Philos. Soc. 131 (2001) 309-319.

[3] See also http://mathworld.wolfram.com/HypergeometricFunction.html

Page 150: manualv2

144 Additional Project Descriptions

Page 151: manualv2

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, PrenticeHall, 1999. ISBN 0-13-011381-6

8. DFIELD and PPLANE java at http://www.prenhall.com/divisions/esm/app/ode/. Seealso http://math.rice.edu/∼dfield.

9. MATLAB and SIMULINK files described in this manual are available athttp://math.asu.edu/∼bdw/PUBLIC

General texts on MATLAB

1. Duane Hanselman and Bruce R. Littlefield, Mastering MATLAB 6, Prentice Hall, 2000. ISBN0-13-019468-9

2. Edward B. Magrab, Shapour Azarm, Balakumar Balachandran, James Duncan, Keith Herold andGregory Walsh, An Engineer’s Guide to MATLAB, Prentice Hall, 2000. ISBN 0-13-011335-2

3. Peter Linz and Richard L. C. Wang, Exploring Numerical Methods: An Introduction to ScientificComputing Using MATLAB, Jones and Bartlett Publishers, 2003. ISBN 0-7637-1499-2

4. William J. Palm III, Introduction to MATLAB 6 for Engineers: with 6.5 Update, McGraw-Hill,2001. ISBN 0-07-283300-9

5. Rudra Pratap, Getting Started with MATLAB: A Quick Introduction for Scientists and Engineers,Oxford University Press, 2002. ISBN 0-19-515014-7

145

Page 152: manualv2

146 References

Appendix: MATLAB Quick Reference

Below is presented a quick reference help for essential MATLAB commands in the Ordinary DifferentialEquations context. A wealth of information and examples is also available using the Help > Matlabhelp menu or at the web site

http://www.mathworks.com

At this site links can be found to other sites, books, and products dealing with MATLAB, SIMULINK,and applications to various fields of Mathematics and Science.

1. General Commands

Command Description Exampleexit or quit terminate MATLAB sessionhelp display m-file help in Command Window help ode45= assign value x=2; return, cancel output x=2;, separator x=2, y=4; (only x is output)... line continuation y=x ...

+2;% comment theta=45; % anglepause halt execution temporarily pause, pause(2)ans most recent answer x=2; 2*ans, x=3; 2*ans

2. Mathematical Constants, Operations, and Functions

Command Description Example+,-,*,/,^ add, subtract, multiply, divide, power x=2; (2/3)*(x+2)^3-10Inf, NaN infinity , Not-a-Number (output) 1/0, 0/0pi, exp(1), i constants π, e,

√−1 exp(1)^(i*pi), exp(i*pi)NOTE: if i has been used oth-erwise (e.g. as loop index) usesqrt(-1) instead

cos, sin, tan,cot, sec, csc

trigonometric functions sin(pi/3)-sec(x^2)

acos, asin, atan,acot, asec, acsc

inverse trigonometric functions acos(0.6)

sqrt square root sqrt(42)exp exponential exp(2)log natural logarithm log(exp(1))log10 logarithm base 10 log10(100)abs absolute value abs(-3)conj Complex conjugate conj(2+3*i)real, imag real, imaginary part z=2+3*i; real(z), imag(z)round round to nearest integer round(3.7)inline construct a function f=inline(’exp(-t)’,’t’)eval interpret MATLAB strings eval(’cos(pi)’)feval function evaluation feval(f,3) same as f(3)function construct an m-file function function gv=g(t)

gv=exp(-t)@ m-file function handle feval(@g,3)

Page 153: manualv2

References 147

3. Array Creation and Manipulation

Command Description Example[, ] array definition x=[1,2,3]

string concatenation str=[’x = ’ num2str(x)], (comma) ; column, row separators A=[1,2;3,4;5,6]: (colon) regularly spaced vector

index into arrayrearrange

x=1:2:9A(2:3,:)x(:)

’ transpose x’linspace linearly spaced vectors linspace(1,9,5)logspace logarithmically spaced vectors logspace(-5,0,6)eye identity matrix eye(5,5)zeros array of all zeros zeros(5,3)ones array of all ones ones(5,3)rand uniformly distributed random numbers rand, rand(10,1)randn normally distributed random numbers randn, randn(10,1)magic magic square magic(4)save save variable to file save ’data.mat’ x Aload retrieve variables from file load ’data.mat’ x Alength length of vector length(x)size array dimensions size(x), size(A)end last index in array x(end), A(end,1).*,./,.^ entry-wise multiply, divide, power x=[1,2,3]; y=1:3;

x.^2.*y./(1+x)min, max minimum, maximum elements of an array min(x), max(max(A))sort sort elements in ascending order y=sort(x)find find indices and values of nonzero elements i=find(x), [i,j]=find(A)sum sum of array elements (along first direction) sum(1:10), sum(A)cumsum cumulative sum cumsum(1:10)mean average or mean value of arrays mean(x)prod product of array elements prod(x)

4. General Display, Evaluation

Command Description Exampleclc clear Command Window clcformat display format for output format compactdiary save MATLAB session to file diary ’session1’disp, ’ display text or array disp(’Having fun?’)

disp([’x=’ num2str(x)])int2str integer to string conversion disp([’i=’ int2str(i)])num2str number to string conversion disp([’x=’ num2str(x)])tic...toc

stopwatch timer tic[t,y]=ode45(@f,[0,20],1);toc

input user input N = input(’How many? N = ’)str = input(’Name ? = ’,’s’)

figure create/raise figure window figure(2)subplot create axes in tiled positions subplot(2,1,2)plot plot vectors or matrices plot(t,y,’r-’)plot3 plot lines and points in 3D plot3(x,y,z,’r-’)

Page 154: manualv2

148 References

Command Description Examplesemilogxsemilogy

semi-log scale plot semilogy(t,y,’r-’)NOTE: negative values are ignored

meshgrid generate arrays for 3D plots [X,Y]=meshgrid(0:.1:1,0:.1:2)surf 3-D shaded surface graph surf(X,Y,Z)contour contour (level curves) plot contour(X,Y,Z)quiverquiver3

2D/3D quiver (or velocity) plot quiver(X,Y,dX,dY)

drawnow complete pending drawing drawnowaxis axis scaling axis equal, axis([0,1,0,2])xlimylimzlim

set/get current x, y, z-axis limits xlim([0,2]), xlim

grid grid lines for plots grid on, grid offlegend add legend legend(’f(x)’,’g(x)’)xlabelylabelzlabel

x, y, z-axis labels xlabel(’time t’)

title plot title title(’IVP solution’)text add text to graph text(1,2,’f(x)’)gtext add text to 2D graph with mouse gtext(’f(x)’)print print graph to file print -depsc out.eps

5. Logical Operations and Control Flow

Command Description Example==, ∼=, <, <=, >, >=&, |, ∼

comparisonlogical AND, OR, NOT

if x>=2 & y∼=0z=sqrt(x-2)/y;end

any, all test for any/all nonzeros any([0,1,2])for ......

end

repeat statements for i=2:10x(i)=x(i-1)+1;

endwhile ......

end

indefinitely repeat statements while e<tolx(i)=x(i-1)+1; e=max(x);

endif ......

elseif ......

else...

end

conditionally execute statements if x==0y=1;

elseif x==piy=-1;

elsey=pi*sin(x)/(x*(x-pi));

endswitch ...case ......

case ......

otherwise...

end

switch among cases switch xcase 0y=1;

case piy=-1;

otherwisey=pi*sin(x)/(x*(x-pi));

endbreak terminate current execution breakcontinue pass control to next iteration continuereturn return to invoking function return

Page 155: manualv2

References 149

6. Algebra, Calculus, and Differential Equations

Command Description Exampleinterp1 1D data interpolation y = interp1(xdata,ydata,x)quad/quadl adaptive quadrature quad(’1./(1+x.^2)’,0,2)fminsearch minimize function fminsearch(’(x-1).^3’,0)fzero find zero of 1D function fzero(’(x-1).^2’,0)

NOTE: needs sign changeodeset set IVP solver options odeset(’RelTol’,1e-6,’AbsTol’,1e-6);ode23ode45ode15sode23sode23t

IVP solver [t,y]=ode45(@f,[0,20],y0);[t,y]=ode45(@f,[0,20],y0,[],param);[t,y]=ode45(@f,[0,20],y0,options,param);

roots polynomial roots roots([1,4,3])poly polynomial given roots

characteristic polynomialpoly([-1,-3])poly(A)

det matrix determinant det(A)eig eigenvalues, eigenvectors [X,D]=eig(A)

ev=eig(A)trace sum of diagonal elements trace([1,2;3,4])norm vector and matrix norms norm(A)null null space of a matrix null(A)expm matrix exponential expm(A)

NOTE: do not confuse with exp(A)\ system solve A\b

7. SIMULINK Blocks

Block Name Symbol Library

Integrator Continuous

State-Space Continuous

Transfer Fcn Continuous

Fcn Functions

Gain Math

Product Math

Slider Gain Math

Sum Math

Mux, Demux Signals & Systems

Scope Sinks

XY-Graph Sinks

Constant Source

Sine Wave Source


Recommended