Matlab Workbook: CME 102 Winter 2008-2009
Matlab Workbook: CME 102 Winter 2008-2009
Matlab Workbook: CME 102 Winter 2008-2009
Eric Darve
Hung Le
2/55 CME 102 Matlab Workbook 2008-2009
Introduction
This workbook aims to teach you Matlab and facilitate the successful integration of Matlab into the
CME 102 (Ordinary Differential Equations for Engineers) curriculum. The workbook comprises
three main divisions; Matlab Basics, Matlab Programming and Numerical Methods for Solving
ODEs. These divisions are further subdivided into sections, that cover specific topics in Matlab.
Each section begins with a listing of Matlab commands involved (printed in boldface), continues
with an example that illustrates how those commands are used, and ends with practice problems
for you to solve.
The following are a few guidelines to keep in mind as you work through the examples:
a) You must turn in all Matlab code that you write to solve the given problems. A convenient
method is to copy and paste the code into a word processor.
b) When generating plots, make sure to create titles and to label the axes. Also, include a legend
if multiple curves appear on the same plot.
c) Comment on Matlab code that exceeds a few lines in length. For instance, if you are defining
an ODE using a Matlab function,explain the inputs and outputs of the function. Also, include
in-line comments to clarify complicated lines of code.
Good luck!
CME 102 Matlab Workbook 2008-2009 3/55
1 Matlab Basics
1.1 Matrix and Vector Creation
Commands:
Note: More information on any Matlab command is available by typing help command name(without
the quotes) in the command window.
1.1.1 Example
a) Create a matrix of zeros with 2 rows and 4 columns.
b) Create the row vector of odd numbers through 21,
L =
1 3 5 7 9 11 13 15 17 19 21
A =
2 3 2
1 0 1
4/55 CME 102 Matlab Workbook 2008-2009
Solution:
a) >> A = zeros(2,4)
A =
0 0 0 0
0 0 0 0
b) >> L = 1 : 2 : 21
L =
1 3 5 7 9 11 13 15 17 19 21
c) >> S = sum(L)
S =
121
d) >> A = [2, 3, 2; 1 0 1]
A =
2 3 2
1 0 1
1.2.1 Example
a) Create two different vectors of the same length and add them.
f) Create a 3 3 matrix and display the first row of and the second column on the screen.
Solution:
c =
6 3 4
b) >> c = a - b
c =
-2 -1 2
c) >> c = a .* b
c =
8 2 3
d) >> c = a ./ b
c =
e) >> c = a .^ 2
c =
4 1 9
ans =
1 2 3
6/55 CME 102 Matlab Workbook 2008-2009
ans =
2
3
5
a =
5 3 1
b =
1 3 5
f) Create a 3 3 matrix and display the first row of and the second column on the screen.
1.3.1 Example
Let us plot projectile trajectories using equations for ideal projectile motion:
1
y(t) = y0 gt2 + (v0 sin(0 )) t,
2
x(t) = x0 + (v0 cos(0 )) t,
where y(t) is the vertical distance and x(t) is the horizontal distance traveled by the projectile
in metres, g is the acceleration due to Earths gravity = 9.8 m/s2 and t is time in seconds. Let
us assume that the initial velocity of the projectile v0 = 50.75 m/s and the projectiles launching
angle 0 = 5
12 radians. The initial vertical and horizontal positions of the projectile are given by
y0 = 0 m and x0 = 0 m. Let us now plot y vs. t and x vs. t in two separate graphs with the vector:
t=0:0.1:10 representing time in seconds. Give appropriate titles to the graphs and label the axes.
Make sure the grid lines are visible.
Solution:
x(t) vs. t
150 y(t) vs. t
150
Altitude (m)
100
50 50
0 0
0 5 10 0 5 10
Time (s) Time (s)
The time vectors for these angles should be defined as t = 0:0.1:9 and t = 0:0.1:8 respectively.
Note: Make sure that when you use the "hold" command to make multiple plots, you should
specify the color and/or line style in the plot command. Otherwise all the plots will be of the
same default (blue) color and line style. Check this out.
1.4.1 Example
a) Using the plot command for multiple plots, plot y = sin(x) and y = cos(x) on the same
graph for values of x defined by: x = 0:pi/30:2*pi.
b) Using the plot command for a single plot and the hold commands, plot y = sin(x) and
y = cos(x) on the same graph for values of x defined by: x = 0:pi/30:2*pi.
2
c) Using the ezplot command, plot y = 3 cos(x) for values of x such that 0 x 2 pi.
Solution:
>> ezplot((2/3)*cos(pi*x),[0,2*pi]);
>> title(High Frequency Cosine Function);
>> xlabel(x);
>> ylabel(y);
>> grid on;
10/55 CME 102 Matlab Workbook 2008-2009
0.5
0
y
0.5
0 1 2 3 4 5 6
x
b) Using the plot command for a single plot and the hold commands, plot y = atan(x) and
y = acot(x) on the same graph for values of x defined by x = -pi/2:pi/30:pi/2.
c) Using the ezplot command, plot y = 32 sin(9x), for values of x such that 0 x 2 pi.
1.5.1 Example
Graph the efficiency of several programming algorithms according to big-O notation, a method
of describing the running time of algorithms. Each expression represents the scale by which an
algorithms computation time increases as the number of its input elements increases. For example,
O(n) represents an algorithm that scales linearly, so that its computation time increases at the
same rate as the number of elements. The algorithms you must graph have the following big-O
CME 102 Matlab Workbook 2008-2009 11/55
characteristics:
After generating an initial graph with ranging from 0 to 8, use logarithmic scaling on the y-axis
of a second graph to make it more readable. You can also use the mouse to change the y-axis
scale. Go to the main menu of the figure, click Edit>Axes Properties. . . , the property editor dia-
logue will pop out. There, you can also change the font, the range of the axes, . . . Try to play with it.
Solution:
>> n=0:0.01:8;
>> plot(n,n,n,n.^2,n,n.^3,n,2.^n,n,exp(n))
>> title(Big-O characteristics of Algorithms: Linear Plot)
>> ylabel(Estimate of Running Time)
>> xlabel(n (number of elements))
>> legend(O(n),O(n^2),O(n^3), O (2^n),O(e^n))
>> grid on;
3
O(n )
2000
O (2n)
O(en)
1500
1000
500
0
0 2 4 6 8
n (number of elements)
>> n = 0:0.01:8;
>> semilogy(n,n,b,n,n.^2,r,n,n.^3,g,n,2.^n,c,n,exp(n),k)
>> title(Big-O characteristics: Logarithmic Plot)
>> ylabel(Estimate of Running Time)
>> xlabel(n (number of elements))
>> legend(O(n),O(n^2),O(n^3), O(2^n),O(e^n))
12/55 CME 102 Matlab Workbook 2008-2009
2
10
2 O(n)
10
O(n2)
O(n3)
4
10
O(2n)
O(en)
6
10
0 2 4 6 8
n (number of elements)
2 Matlab Programming
2.1 for and while Loops
Commands:
for i = a:b The for loop repeats statements a specific number of times, starting
with i = a and ending with i = b, incrementing i by 1 each iteration
of the loop. The number of iterations will be b - a + 1.
while condition The while loop repeats statements an indefinite number of times as
long as the user-defined condition is met.
for i = a:h:b The for loop works exactly the same except that i is incremented by
h after each iteration of the loop.
clear Clears all previously defined variables and expressions.
fprintf Outputs strings and variables to the Command Window. See below
for an example.
abs(x) Returns the absolute value of the defined variable or expression x.
factorial(n) Returns the factorial of the defined variable or expression n.
CME 102 Matlab Workbook 2008-2009 13/55
... The ellipses can be used to break up long lines by providing a contin-
uation to the next line. Strings must be ended before the ellipses but
can be immediately restarted on the next line. Examples below show
this.
Note: Neglecting the command clear can cause errors because of previously defined variables in
the workspace.
fprintf:
This is an example of how to use fprintf to display text to the command window.
fprintf (\nOrdinary Differential Equations are not so ordinary.\n);
fprintf (-------------------------------------------------------...
----------------\n);
fprintf (This course is CME %g: ODEs for Engineers. My expected...
grade is %g\n,102,100);
x = 100; y = 96;
fprintf (The previous course was CME %g: Vector Calculus for ...
Engineers. My grade was: %g\n,x,y);
The Matlab command window displays:
Ordinary Differential Equations are not so ordinary.
-----------------------------------------------------------------------
This course is CME 102: ODEs for Engineers. My expected grade is 100
The previous course was CME 100: Vector Calculus. My grade was: 96
The command fprintf takes a string and prints it as is. The character \n is one of several Escape
Characters for fprintf that can be placed within strings given to fprintf. \n specifies a new
line. %g is one of many Specifiers that fprintf uses and it represents a placeholder for a value
given later in the call to fprintf. The order of the arguments given to fprintf determine which
%g is replaced with which variable or number. Experiment with the code above to see what \n can
do and how %g can be used.
M-Files/Scripts:
Everything we have done so far has been in MATLABs interactive mode. However, MATLAB can
execute commands stored in a regular text file. These files are called scripts or M-files. Instead
of writing the commands at the prompt, we write them in a script file and then simply type the
name of the file at the prompt to execute the commands. It is almost always a good idea to work
from scripts and modify them as you go instead of repeatedly typing everything at the command
prompt.
A new M-file can be created by clicking on the New M-file icon on the top left of the Command
Window. An M-file has a .m extension. The name of the file should not conflict with any existing
MATLAB command or variable.
Note that to execute a script in an M-file you must be in the directory containing that file. The
14/55 CME 102 Matlab Workbook 2008-2009
current directory is shown above the Command Window in the drop down menu. You can click
on the . . . icon, called Browse for folder, (on the right of the drop-down menu) to change the
current directory. The % symbol tells MATLAB that the rest of the line is a comment. It is a good
idea to use comments so you can remember what you did when you have to reuse an M-file (as will
often happen).
It is important to note that the script is executed in the same workspace memory as everything
we do at the prompt. We are simply executing the commands from the script file as if we were
typing them in the Command Window. The variables already existing before executing the script
can be used by that script. Similarly, the variables in the script are available at the prompt after
executing the script.
2.1.1 Example
After your 30 years of dedicated service as CEO, TI has transfered you to a subdivision in the
Himalayas. Your task as head of the subdivision is to implement transcendental functions on the
Himalayan computers. You decide to start with a trigonometric function, so you find the following
Taylor Series approximation to represent one of these functions:
x3 x5 x2n+1
sin(x) = x + + (1)n + ...
3! 5! (2n + 1)!
However, since the computers in the Himalayas are extremely slow (possibly due to the high alti-
tudes), you must use the Taylor Series as efficiently as possible. In other words, you must use the
smallest possible number of terms necessary to be within your allowed error, which is 0.001. You
will use x = 3 as the value at which to evaluate the function.
a) Compute and display the exact error of using the first 2 and 5 terms of the series as compared
to the actual solution when the function is evaluated at x = 3 .
b) Compute and display the number of terms necessary for the function to be within the allowed
error.
Solution:
clear;
x = pi/3;
end
SIN_Error5 = abs(SIN_Approx5 - sin(x));
OUTPUT:
clear;
SIN_APP = 0; % This is the sine approximation.
n = 0; x = 3;
OUTPUT:
Number of Terms Needed for the function to be within the allowed error:
-----------------------------------------------------------------------
sin(3): 6 terms | Error = 0.000245414
16/55 CME 102 Matlab Workbook 2008-2009
b) Using a while loop, compute and display the number of terms necessary for this function to
have an error within your allowed range of 0.001 when evaluated at x = 3. Display this error.
2.2.1 Example
Matlab is capable of symbolically computing the derivatives and integrals of functions. This can
be very convenient to check your pencil and paper solutions; in some cases Matlab may be able to
integrate functions which require very difficult change of variables. We will also learn in the next
section how Matlab can be used to symbolically solve differential equations. For now we focus on
derivatives and integrals.
The first step is to define symbolic variables using the syms command. Note that symbolic variables
are different from numerical variables. They can not assume any numerical value. They are simply
symbols or letters that can be manipulated symbolically.
Once these variables are declared we can define symbolic functions, differentiate and integrate them
as is shown in the following examples:
f (x) = x2 ex 5x3 .
b) Compute the integral, and the first and second derivatives of the above function symbolically.
CME 102 Matlab Workbook 2008-2009 17/55
f (x, y, z) = x2 ey 5z 2 .
Compute the integral with respect to x and second derivative with respect to z.
Solution:
a) >> syms x
>> f = x^2*exp(x) - 5*x^3;
b) >> int(f)
ans =
x^2*exp(x)-2*x*exp(x)+2*exp(x)-5/4*x^4
>> diff(f)
ans =
2*x*exp(x)+x^2*exp(x)-15*x^2
>> diff(f,2)
ans =
2*exp(x)+4*x*exp(x)+x^2*exp(x)-30*x
c) >> syms x y z
>> f = x^2*exp(y) - 5*z^2;
>> int(f,x)
ans =
1/3*x^3*exp(y)-5*z^2*x
>> diff(f,z,2)
ans =
-10
x
c) Compute the first and the second derivatives of atan .
5
18/55 CME 102 Matlab Workbook 2008-2009
2.3.1 Example
Before considering the examples, the following points are to be noted:
The letter D denotes differentiation with respect to the independent variable. The symbolic
d2 y d3 y
specification of dy
dt is Dy. Higher order derivatives such as dt2 , dt3 etc. are specified as
D2y, D3y and so on.
By default, the independent variable is t. The independent variable may be changed from t
to some other symbolic variable by including that variable as the last input argument of the
dsolve command. For example, the following equation has x as the independent variable:
dy
=kx
dx
and to solve the above for its general solution, the syntax is:
dsolve(Dy = k*x,x)
dy
= ey
dt
y(0) = 0
Solution:
b) >> dsolve(D2y-Dy=1+t*sin(t))
ans =
-1/2*cos(t)-1/2*t*sin(t)-sin(t)+1/2*cos(t)*t+exp(t)*C1-t+C2
c) >> dsolve(Dy=exp(-y),y(0)=0)
ans =
log(t+1)
d) dsolve(Dy+K*y = A+B*cos((1/12)*pi*t),y(0)=0)
ans =
exp(-K*t)*(-144*B*K^2-A*pi^2-144*A*K^2)/(144*K^3+K*pi^2)
+(144*A*K^2+A*pi^2+144*B*K^2*cos(1/12*pi*t)
+12*B*pi*sin(1/12*pi*t)*K)/K/(144*K^2+pi^2)
dy
y = e2t .
dt
d2 y dy
2
+ 8 + 16y = 0.
dt dt
y(0) = 5.
20/55 CME 102 Matlab Workbook 2008-2009
3 Forward Euler
Commands:
Forward Euler presents the most basic way to solve a differential equation numerically. Even though
it has the most stringent stability criterion and the lowest accuracy of all numerical solvers, it is
the simplest and easiest to program. In this section, we will explore:
The forward Euler algorithm is an explicit means of obtaining the value of y at each time step using
the previous time step and the local slope or derivative. The equation is derived from approximating
the derivative y 0 with the difference quotient
yn+1 yn
yn0 = f (tn , yn ).
h
As the boxed algorithm expresses, we solve for each subsequent time step yn+1 by adding the
approximate change in y to the previous value of y. The last statement in the equation follows
our convention of designating the slope or derivative as the function f (tn , yn ). Thus, by decreasing
the time step h by which we march across our interval, we can make our solution more and more
accurate. This algorithm is explicit because all values for the next time step are readily isolable
from previous known values, making evaluation simple and systematic.
To solve any ordinary differential equation that is expressible in the explicit form
yn0 = f (tn , yn ),
we pass a Matlab function yprime.m that contains the code for computing f (tn , yn ) to another
function, say, forwardEuler.m. (The latter performs the numerical integration according to the
forward Euler method.) Once we have the forward Euler algorithm implemented in Matlab, we
CME 102 Matlab Workbook 2008-2009 21/55
need alter only the function yprime.m when we change differential equations. (Copy the code below
and use it for future problems.)
Although not shown in the definition of the function forwardEuler.m (below), when you run the
code, Matlab uses a handle to pass the function yprime.m to forwardEuler.m. Handles are
denoted using the at (or around) character, @; e.g., to call the function forwardEuler.m
(after creating your own function yprime.m), type
>> forwardEuler(@yprime, tspan,h,y0)
in the Matlab command window. (Make sure your current directory setting in Matlab is set
to the directory containing yprime.m and forwardEuler.m.) Inside of forwardEuler.m, you can
directly use your function using yprime(t,y).
Use the following forward Euler script to solve any first-order ODE given a domain and an initial
condition (these should be input parameters). Name the file, say, forwardEuler.m. The ODE
must assume the following form:
y 0 = f (t, y)
y(t0 ) = y0
CODE from forwardEuler.m
function [T,Y] = forwardEuler(yprime,tspan,h,y0)
% Initializing n:
n=1;
3.1 Example
Implementation of Forward Euler
a) Solve the following ODE using your script and plot the solution along with the exact solution
on the same plot.
y 0 = t2 + y, 0t2
y(0) = 1
h = 0.25
yexact = 3et t2 2t 2
b) Compute solutions to the ODE in the above example for h = 0.5, 0.25, 0.1, and 0.01 with
all other parameters remaining the same. Plot these four solutions along with the exact
analytical solution on the same graph. Adjust line styles using the figure menus.
Solution:
% ODE
function yprime = yprime(t,y)
yprime = t^2 + y;
% Exact solution
function yexact = yexact(t)
yexact = 3*exp(t) - t.^2 - 2*t - 2;
t = 0 : 0.01 : 2;
plot(t, yexact(t),r)
title(Analytical and Numerical Solutions of dy/dt = t^2 + y)
xlabel(x)
ylabel(y)
legend(Numerical Solution, Analytical Solution,...
Location,NorthWest)
hold off
clear;
h = [0.01 0.1 0.25 0.5];
for i=1:4;
[T,Y] = forwardEuler(@yprime,[0 2],h(i),1);
CME 102 Matlab Workbook 2008-2009 23/55
plot(T,Y)
hold on;
end
10
8
y
0
0 0.5 1 1.5 2
x
0 0.5 1 1.5 2
x
24/55 CME 102 Matlab Workbook 2008-2009
Accuracy
As the results from the above example illustrate, numerical solutions introduces error, not only in
each single step that we take but also across the entire interval. Thus, to measure the accuracy of
the numerical method, we designate the single step error as the local error and the accumulated
error over an interval as the global error. To calculate the local error at a given step, we simply
calculate the absolute value of the difference between the exact solution and the numerical solution
for that step. For example, for the i th step:
Local (or) Single step error = y exact (t0 + ih) yinumerical .
Calculating the global error involves a bit more complication as to how to combine the effects of
the single step errors. A widely used method is to calculate the Euclidean norm, which involves
estimating the accumulation of error as follows:
s
Pn exact 2
i=1 y
(t0 + ih) yinumerical
Global error =
n
= norm(y exact y numerical)/sqrt(n) in Matlab,
3.2 Example
a) Compute the global error in 8.1.1 a) using the Euclidean norm. Use the length command to
calculate the number of time steps n.
b) Compute and display the global error for h = 0.1, 0.01, 0.001, 0.0001.
Solution:
a) CODE from M-file
clear;
%tspan = [tmin tmax]: interval over which solution has to be computed.
tspan = [0 2];
h = 0.25;
[T,Y] = forwardEuler(@yprime,tspan,h,1);
Output
clear;
tspan = [0 2];
h = [0.1 0.01 0.001 0.0001];
for j = 1:4
[T,Y] = forwardEuler(@yprime,tspan,h(j),1);
% Recompute number of time steps for each iteration
n = length(Y);
% Calculate global error using the Euclidean norm
TimeStep = h(j);
ErrG_Euc(j) = norm(yexact(T)-Y)/sqrt(n);
Global_Error = ErrG_Euc(j);
fprintf(TimeStep = %.4f, Global Error = %.4f\n,TimeStep, Global_Error);
end
Output
Order of Accuracy
The accuracy that we calculated in the previous exercise applies only to the specific differential
equation we solved. To describe the accuracy of the forward Euler method more generally, we
estimate a quantity called the order of accuracy that describes the relationship between accuracy
and time step. For example, a numerical scheme with a global accuracy of O(h) has an order of
accuracy 1. Such a scheme will generally produce a solution that is half as accurate when we double
the step size. Likewise, when we halve the step size, the accuracy increases by a factor 2. Thus
a higher order of accuracy is generally preferable, since only a small improvement in step size is
required to effect a greater decrease in error.
Once we determine the local order of accuracy, the global order of accuracy is usually one or-
der lower. For example, if the local order of accuracy is 2, then the global order of accuracy is 1.
The global accuracys lower order results from the fact that errors accumulate with each step. Let
us look at this more precisely.
For our example before, the local error can be shown to be O(h2 ) using a Taylors series expansion
of the solution. The global error is the accumulation of local errors over n steps:
tf t0
In general, if n = h is the number of (time) steps and the local error at each step is O(hn ),
then:
Global error = n.O(hn )
tf t0
= O(hn )
h
= O(hn1 ).
Thus the global order of accuracy is n 1.
Stability
As it results in an explicit equation, the forward Euler method has a finite stability interval, outside
of which the solution diverges (blows up to ). To obtain an equation for the stability interval,
we use the model differential equation:
y 0 = y
Applying the forward Euler scheme to the model equation, we get:
yn+1 = yn + h.yn0
= yn + h. (yn )
= yn (1 + h)
yn = (1 + h)n y0
To prevent the numerical solution from blowing up, the factor (1 + h) should not exceed unity;
that is |1 + h| 1. It can be seen that the numerical solution will quickly approach infinity once
the absolute value of this factor exceeds unity.
3.3 Example
Let us consider the model equation:
dy(t)
= 2y(t) ( = 2).
dt
To determine the stability interval for the forward Euler method, we make use of the fact that
|1 + h| < 1 for a decaying solution. This means:
|1 2h| < 1 0 < h < 1.
Given below are plots of the numerical solution for h = 0.1, 0.6 and 1.1 with t = 0 to 20 and
y(0) = 1.
Numerical solution of y(t) = 2t using forward Euler method with h = 0.1
1
0.8
0.6
y(t)
0.4
0.2
0
0 5 10 15 20
t
CME 102 Matlab Workbook 2008-2009 27/55
0.8
0.6
y(t)
0.4
0.2
0.2
0 5 10 15 20
t
20
10
y(t)
10
20
30
0 5 10 15 20
t
It can be clearly seen from the above plots that for h > 1, the numerical solution oscillates and
diverges (is unbounded). This means the forward Euler scheme applied to this ordinary differential
equation is not stable for h > 1. For both h = 0.6 and h = 0.1, the forward Euler scheme is stable.
For h = 0.6, the numerical solution oscillates in an un-physical way but it decays as t increases.
Therefore it is still stable.
a) The software package loaded on your spaceship specifies the following model for the popula-
tion:
K P0
P (t) =
P0 + (K P0 )ert
where K is the carrying capacity (maximum value) of the population, P0 is the initial pop-
ulation and r is the reproductive rate. Based on experimental data, you can approximate
these parameters of the model using the following:
Reproductive Rate: r = 1
t ln PP(2t)(P (t)P0 )
0 (P (2t)P (t))
.
Note: The computed reproductive rate r is more accurate if points that are farther apart are
used for computation(i.e. points which are separated by a large t).
Using these formulas, compute the parameters K, P0 , and r for this model. Write down the
best fit P (t) using the computed values of the parameters. Evaluate the goodness of the fit
by comparing the difference between the data and the model.
Plot the experimental data and the model on the same figure. In which month is the difference
between the data and the model largest? How big is this difference?
b) The population model given above corresponds to the logistic growth model given by
P (t)
P 0 (t) = r P (t) 1
K
Solve the logistic growth model using Forward Euler with a time step of 0.1, and plot it along
with the previous analytical model which was specified by the software.
c) Assuming that the model specified by the software in part a) is the analytical solution of the
differential equation in part b), what is the Euclidean global error of your numerical logistic
model obtained using Forward Euler? The expression for the Euclidean global error is given
by:
s
Pn exact yinumerical |2
i=1 |yi
Global Error =
n
||y exact y numerical ||
=
n
4 Improved Euler
Improved Euler represents an improved version of Forward Euler not only because it is more accu-
rate but also because it boasts a larger stability interval. At the expense of increased algorithmic
complexity, each time step produces a closer solution to the exact result than Forward Euler. In
this section, we will explore:
k1 = f (tn , yn
k2 = f (tn+1 , yn + k)
yn+1 = yn + h 12 (k1 + k2 )
The Improved Euler algorithm is still explicit, as the next step is explicitly expressed in terms of
values at the current step. However, unlike Forward Euler, the Improved Euler algorithm introduces
the slopes at two different points.
As before, we pass in the function f (tn , yn ) so that we can solve any ordinary differential equation
expressible in the explicit form yn0 = f (tn , yn ). Once we have programmed Improved Euler, we
need alter only the function yprime.m when we change differential equations.
Use the following Improved Euler script to solve any first-order ODE given a domain and an initial
condition (these should be input parameters). Name the file ImprovedEuler.m.
T(1) = tspan(1);
Y(1) = y0;
n=1;
T(n+1) = T(n) + h;
k1 = h * yprime(T(n),Y(n));
k2 = h * yprime(T(n+1),Y(n)+k1);
Y(n+1) = Y(n) + (1/2) * (k1+k2);
n=n+1;
end
4.1 Example
Implementation of Improved Euler
a) Solve the following ODE using your script and plot the solution along with the exact solution
on the same plot. On the same plot, graph the solutions for h = 2, h = 4, h = 5.
y 0 = ey , y(0) = 0
t0 = 0, tf = 20
h = 2, 4, 5
yexact = ln(t + 1)
Solution:
% Exact solution
function yexact = yexact(t)
yexact = log(t+1);
clear;
h = [2 4 5];
for i=1:3;
[T,Y] = ImprovedEuler(@yprime,[0 20],h(i),0);
plot(T,Y)
hold on;
end
2.5
y
1.5
1 h=2
h=4
0.5 h=5
Analytical Solution
0
0 5 10 15 20
x
b) Compute the global error and the local error of Improved Euler by solving the above equa-
tion with h = 5. Display both errors. Use length in calculating the number of time steps.
Solution:
clear;
% tspan = [tmin tmax] : interval over which solution has to be computed
tspan = [0 20];
h = 5;
[T,Y] = ImprovedEuler(@yprime,tspan,h,0);
Output
Order of Accuracy
The Improved Euler method represents an improvement in accuracy over the Forward Euler method.
The Improved Euler method has a local order of accuracy of O(h3 ) and more importantly a global
order of accuracy of O(h2 ). This is an order better than the Forward Euler method, which has a
32/55 CME 102 Matlab Workbook 2008-2009
global order of accuracy of O(h). This improvement in accuracy is achieved through the introduction
of intermediate calculations. The Improved Euler method is sometimes also referred to as the
Runge-Kutta 2 method for its second order global accuracy.
Stability
Just like the Forward Euler method, the Improved Euler method also results in an explicit equation.
This results in a finite stability interval, outside of which the solution diverges (blows up to ).
To obtain an equation for the stability interval, we use the model differential equation:
y 0 = y.
h2 2
To prevent the numerical solution from blowing up, the factor 1 + h + should not exceed
2
unity; that is:
2 2
1 + h + h 1.
2
4.2 Example
c) Plot the stability intervals for the Forward Euler method and the Improved Euler methods.
Solution
CME 102 Matlab Workbook 2008-2009 33/55
2
3 2 1 0 1
hx
34/55 CME 102 Matlab Workbook 2008-2009
5 Runge-Kutta 4 (RK4)
Runge-Kutta 4 extends the tactic seen in Improved Euler even further by introducing four inter-
mediate slope calculations to determine each step with even greater accuracy and stability. While
the method demands more calculation per time step, the resulting solution stays much closer to
the exact solution because the intermediate calculations determine the net change more accurately.
However, because Runge-Kutta 4 is still an explicit method like Forward Euler and Improved Euler,
it, too, is only conditionally stable. In this section, we will explore:
The algorithm and code used to program Runge-Kutta 4
Application of Runge-Kutta 4 to solving differential equations
Runge-Kutta 4s order of accuracy
Runge-Kutta 4s stability limitations
k1 = h f (tn , yn )
k1
k2 = h f tn + h2 , yn + 2
k2
k3 = h f tn + h2 , yn + 2
k4 = h f (tn + h, yn + k3 )
yn+1 = yn + 61 (k1 + 2k2 + 2k3 + k4 )
CME 102 Matlab Workbook 2008-2009 35/55
The Runge-Kutta 4 algorithm is still explicit, as the next step is explicitly expressed in terms of
values at the current step. However, unlike the Euler methods, Runge-Kutta 4 takes several half-
steps to gauge the slope between points before returning to make a full step. The final calculation
uses a complex averaging of several derivatives.
As before, we pass in the function f (tn , yn ) so that we can solve any ordinary differential equation
expressible in the explicit form yn0 = f (tn , yn ). Once we have programmed Runge-Kutta 4, we need
alter only the function yprime.m when we change differential equations.
Use the following Runge-Kutta 4 script to solve any first-order ODE given a domain and an initial
condition (these should be input parameters). Name the file RK4.m.
T(1) = tspan(1);
Y(1) = y0;
n=1;
a) Solve the following ODE using the Runge-Kutta 4 method and plot the solutions for h = 0.5
36/55 CME 102 Matlab Workbook 2008-2009
and 0.05 along with the exact solution on the same plot.
Solution:
% ODE
function yprime = yprime(t,y)
% dy/dt = t*(y+2)
yprime = t*(y+2);
% Exact solution
function yexact = yexact(t)
yexact = 3*exp(t.^2/2) - 2;
clear;
h = [0.5 0.05];
[T,Y] = RK4(@yprime,[0 3],0.5,1);
plot(T,Y,b);
[T,Y] = RK4(@yprime,[0 3],0.05,1);
hold on;
plot(T,Y,r);
200
100
50
0
0 0.5 1 1.5 2 2.5 3
t
Order of Accuracy
Runge-Kutta 4 (RK4) represents an improvement in accuracy over both the Forward and Improved
Euler methods because of its relatively better approximation of the function slope during every time
step. It has a local accuracy that is O(h5 ) and therefore a global accuracy that is O(h4 ). This
means, by dividing the time step by 10, we can effectively increase the global accuracy by a factor
of 104 . In fact the fourth order global accuracy gives RK4 its name. Even though it requires more
calculations at each time step than the Forward and Improved Euler methods, the end result boasts
a great improvement in terms of accuracy. The following exercises will demonstrate the improved
accuracy of RK4.
Solution:
clear;
% tspan = [tmin tmax] :interval over which solution has to be computed
tspan = [0 3];
h = [0.001 0.01 0.1];
for j = 1:3
[T,Y] = RK4(@yprime,tspan,h(j),1);
38/55 CME 102 Matlab Workbook 2008-2009
loglog(h,ErrG_Euc);
xlabel(h);
ylabel(Global Error);
title(Global Error vs. Time Step);
% Slope calculation:
Global_Error_Slope = (log(ErrG_Euc(3))-log(ErrG_Euc(2))) /(log(h(3))-log(h(2)));
fprintf(Global error slope = %g\n,Global_Error_Slope);
Output
4
10
6
Global Error
10
8
10
10
10
12
10
3 2 1
10 10 10
h
Stability
Since it is explicit, RK4 has a finite stability region. The extra expense involved in the improved
slope calculations widens the stability interval of RK4 in comparison to that of the Forward and
Improved Euler methods. To obtain an equation for this stability interval, let us use the following
model differential equation:
y 0 = y.
Applying the RK4 scheme to the model equation, we calculate the four slopes as follows:
k1 = h f (tn , yn )
CME 102 Matlab Workbook 2008-2009 39/55
= h (yn ),
1
k2 = h yn + k1
2
1
= h yn + hyn
2
1
= hyn + h2 2 yn ,
2
h 1
k3 = h f tn + , yn + k2
2 2
1
= h yn + k2
2
1 1 2 2
= h yn + hyn + h yn
2 2
1 1
= h yn + hyn + h2 2 yn
2 4
1 1
= hyn + h2 2 yn + h3 3 yn ,
2 4
k4 = h f (tn + h, yn + k3)
= h (yn + k3)
1 2 2 1 3 3
= h yn + hyn + h yn + h yn
2 4
1 1
= hyn + h2 2 yn + h3 3 yn + h4 4 yn .
2 4
1 1 1
RK4 : 1 + h + h2 2 + h3 3 + h4 4 1.
2 6 24
Solution
c) CODE from M-file
clear;
x = -3:0.01:1;
% We assume x = h*lambda and select a large range for x to find the
% stability interval.
plot(x,1+x,r,x,1+x+(1/2)*x.^2,g,x,1+x+(1/2)*x.^2+(1/6)*x.^3+(1/24)*x.^4,b);
title(Stability Intervals);
xlabel(h\lambda);
ylabel(f(h\lambda));
legend(Forward Euler method,Improved Euler method,RK4);
Stability Intervals
3
Forward Euler method
Improved Euler method
2 RK4
1
f(h)
2
3 2 1 0 1
h
It can be seen from the above plot that the stability interval for:
Forward and Improved Euler methods is: 2 h 0
RK4 method is: 2.8 h 0
RK4, because of its bigger stability interval is more stable than the Forward and Improved Euler
methods.
a) Use Forwared Euler and Runge-Kutta 4 with a time step of h = 1 to approximate the speed
of the falling mass at t = 5. Graph the solutions on the same plot.
b) Use dsolve to determine the exact solution, and add it to your plot. Which numerical solution
provides the best approximation?
c) Can you determine the terminal speed (i.e. the speed reached after a long time) from the
plot? How long does it take to reach this speed?
d) Find an analytical expression for the terminal speed in terms of m, g and k. Does it agree
with your answer for part c)?
Input Parameters
To call ode45 or ode113, the following lines must be typed at the command line or in a script.
@yprime Handle of the function defining the ODE to be solved - yprime *must*
output a column vector!
tspan Row vector containing the initial and final time across which we must
solve the ODE
y0 Row vector containing all necessary initial conditions y(0), y 0 (0),
y 00 (0) . . ., or simply y(0) for 1st order ODEs.
options Optional values specifying error tolerance where beforehand we set
options = odeset(reltol,reltol,abstol,abstol). The in-
puts reltol and abstol are scalar values for the relative tolerance
and absolute tolerance, respectively.
Introduction
When we write a numerical ODE solver, it should be able to solve any differential equation that
we can define with a function y 0 = f (x, y). Function handles allow us to input any differential
42/55 CME 102 Matlab Workbook 2008-2009
equation @yprime into our solver as a variable without changing the script or code of our solver.
Without function handles, we would have to create separate solvers for every differential equation we
encounter, since we would be unable to treat the function yprime as a variable in our solver. Thus,
when we type an input with a handle (@yprime), we essentially pass a function into a program,
which then uses the function as a variable.
Matlabs built-in ODE solvers function no differently. In order to solve a differential equation
numerically, we must write a function yprime to represent the ordinary differential equation we
wish to solve; this function takes the form y 0 = f (x, y). Once we have written our differential
equation in the function yprime, we simply pass that function into the ODE solver with a function
handle in front.
For example, suppose we want to solve the differential equation
y 0 (t) + y(t) 2t t2 = 0.
y 0 (t) = t2 + 2t y(t)
Next, we enter Matlab and write a short and simple function (.m file) for this differential equation:
To solve this equation from t = a to t = b, where y(a) = y0, we simple pass the function into a
solver with the function handle in front:
In response, Matlab will solve the equation and store the t-interval as a column vector and the
solution y as the second column vector. Thus, we type [t,y] to denote these outputs.
Note that we never needed to change the solver (ode45) itself. When we wish to change the
differential equation that we want to solve, we simply change the function that we pass into the
solver. We could even create a new file titled yprime2 or derivative or dfdt or whatever we
wished, so that we can keep yprime intact. Thus, function handles allow us to write ODE solvers
that function independently of the input function.
Accuracy Settings
The two parameters reltol and abstol are used to control the accuracy. Matlab adaptively
chooses the time step such that the error at step n satisfies
en max{r|yn |, a},
where r is the relative tolerance and a is the absolute tolerance. Matlab bounds the error with
either an absolute tolerance or the product of relative tolerance and |yn |. The accuracy constraint
depends on the larger of the two: a categorical, scale-independent error known as AbsTol, or an
error scale relative to the solution known as RelTol. Matlab will determine the larger of the two.
To change the relative and absolute tolerance, we use the odeset function:
CME 102 Matlab Workbook 2008-2009 43/55
opts = odeset(reltol,1e-12,abstol,1e-12);
By setting both tolerance levels to 1012 , we force the solver to use a small time step to preserve
our desired accuracy (or error tolerance). Thus, by changing the tolerance levels (or margins of
error), we can control the size of the time step that ode45 takes. Once we have defined opts, we
can then pass it into the solver as the fourth input parameter. ode45 does not work well for very
stringent accuracies.
For very accurate solutions ode113 is preferable. For example if we set an accuracy of 1012 , ode45
takes around 9s with 100,000 evaluations of yprime whereas ode113 takes 1s with only 10,000
evaluations of yprime.
Solving a system of First Order ODEs
Assume we want to solve the system of equations
dR
= R(t) .5F (t)R(t)
dt
dF
= F (t) + .25F (t)R(t)
dt
This is a simplified version of the predator prey model proposed in 1925 by Lotka and Volterra. R(t)
is the prey (or rabbit) and F (t) is the predator (or fox). The F (t)R(t) terms in the two equations
model the interaction of the two populations. The number of encounters between predator and
prey is assumed to be proportional to the product of the populations. Since any such encounter
tends to be good for the predator and bad for the prey, the sign of the F (t)R(t) term is negative
in the first equation and positive in the second.
To solve this system using Matlab, you first need to define a function taking as input the time t
and a vector y containing R and F :
function yp = predator_prey(t,y)
% y(1) is the prey R
% y(2) is the predator F
yp = [y(1) - 0.5*y(1)*y(2); -0.75*y(2) + 0.25*y(1)*y(2)];
In this function the first entry in y contains R and the second contains F . The function returns the
variable yp. Its first entry is dR dF
dt and its second entry is dt . The system can now be easily solved
by typing
>> [t,y] = ode45(@predator_prey,[0 30],[2 1]);
To plot the solution, use the command
plot(t,y(:,1),t,y(:,2))
legend(Rabbit,Fox)
The resultant matrix y has two columns. The first column of y contains the solution R(t) and the
second F (t). The number of rows is clearly equal to the number of time steps. The solution looks
like this:
y10 (t) = y2 ,
44/55 CME 102 Matlab Workbook 2008-2009
7
Rabbit
6 Fox
0
0 5 10 15 20 25 30
y20 (t) = y1 .
b) Write a Matlab code to solve, using a nested function, the following ODE:
y10 (t) = y1 + y2 ,
y20 (t) = y1 ay2 .
where a is set by the user. Use as initial conditions y1 (0) = 0, y2 (0) = 1. Set a = 0.9 and
solve for 0 t 4. Plot the solution.
c) Solve the following ODE using ode45 with relative and absolute error of 1012 :
y 0 (t) = 8 cos(t) 3y 3 ,
y(0) = 1.
The initial time is t = 0, and the end time is t = 10. Plot the solution.
Solution:
a) function exa
y0=[0 1];
tspan=[0 4*pi];
[t,y] = ode45(@yprime,tspan,y0);
plot(t,y(:,1),t,y(:,2));
xlabel(t);
legend(y_1(t),y_2(t));
end
function yp = yprime(t,y)
yp = [y(2);-y(1)];
end
CME 102 Matlab Workbook 2008-2009 45/55
1
y1(t)
y2(t)
0.5
0.5
1
0 2 4 6 8 10 12
t
b) function exb
y0=[0 1];
tspan=[0 4*pi];
a = 0.9;
[t,y] = ode45(@yprime,tspan,y0);
plot(t,y(:,1),t,y(:,2));
xlabel(t);
legend(y_1(t),y_2(t));
function yp = yprime(t,y)
yp = [-y(1)+y(2); y(1)-a*y(2)];
end
end
0.8
0.6
0.4
y1(t)
0.2
y2(t)
0
0 2 4 6 8 10 12
t
c) function exc
y0=1;
tspan=[0 10];
46/55 CME 102 Matlab Workbook 2008-2009
options=odeset(AbsTol,1e-12,RelTol,1e-12) ;
[t,y] = ode45(@yprime,tspan,y0,options);
plot(t,y);
xlabel(t);
ylabel(y(t));
end
function yp = yprime(t,y)
yp = 8*cos(t)-3*y.^3;
end
1.5
0.5
y(t)
0.5
1.5
0 2 4 6 8 10
t
The five principal variables in the model are all functions of time:
The rate of change of the principal variables is given by the following ordinary differential equations:
dp ps p f (t)
= + ,
dt d 1
CME 102 Matlab Workbook 2008-2009 47/55
ds 1 ps p
= (d s ) w k1 2 ,
dt s d
dd 1
= (k1 (d s ) w) ,
dt d
ds 1
= ((d s ) w k2 ) ,
dt s
dd 1
= (k2 (d s ) w) .
dt d
where s and d are the volumes of the shallow and deep oceans respectively.
The following three additional quantities are involved in equilibrium equations in the shallow ocean:
d = 8.64 w = 103
1 = 4.95 102 k1 = 2.19 104
2 = 4.95 102 k2 = 6.12 105
s = 0.12 k3 = 0.997148
d = 1.23 k4 = 6.79 102
We will mainly be interested in studying how the levels of carbon dioxide in the atmosphere (p)
and carbon concentrations in the shallow (s ) and deep ocean (d ) vary with time.
This opens the file SourceTermTable.mat and creates two arrays tdata and fdata in your
workspace. Plot the data with
>> plot(tdata,fdata)
Here fdata indicates the level of pollution f (t) released in the atmosphere as a function of
time.
48/55 CME 102 Matlab Workbook 2008-2009
b) The file SourceTerm.m includes the function SourceTerm which can be used to get the value
of f (t) at any given t (where t is in units of years). We will first verify that the above function
gives the desired output. Plot f (t) as follows. Verify that the plot you obtain is almost the
same as in part a) but much smoother.
>> t = linspace(1000,5000,10000);
>> plot(t,SourceTerm(tdata,fdata,t))
Verify that f (t) = 5.3852 at t = 2007 (the current year!). Evaluate f (t) at t = 2200 and
t = 2400. When does the pollution function f (t) peak?
c) Write a function called carbonODE which defines the ODE to be solved. This function will
use the variables tdata and fdata. The variable y in carbonODE should contain the following
variables in that exact order: p, s , d , s , d The technique of nested functions must be used.
The function carbonODE needs to be defined inside the function carbon. Follow this template:
function carbon(tdata,fdata)
format long
carbonODE(1000,[1 2.01 2.23 2.20 2.26])
function yp = carbonODE(t,y)
f = SourceTerm(tdata,fdata,t);
% Write the content of carbonODE here
end
end
carbon(tdata,fdata)
ans =
0.010264729371666
-0.004225867532479
-0.000000813008130
-0.000010000000000
0.000000975609756
d) Solve the ODE using ode45 by passing carbonODE as a function handle. You need to solve
from t = 1000 to t = 5000 with the following initial values at t = 1000:
p = 1.0
s = 2.01
d = 2.23
s = 2.20
d = 2.26
e) From the graph find out the year when the concentration of CO2 peaks for, the release from
pollution (the function f (t)), the atmosphere, the shallow ocean.
CME 102 Matlab Workbook 2008-2009 49/55
f) Explain the observed changes in carbon concentration. Does it make sense? Why is the deep
ocean important for the global carbon cycle?
g) Suppose there is an industrialist who claims that burning fossil fuels does not result in the
increase of carbon levels in the environment. He supports his claim by saying that even
though year 2004 and 2005 witnessed highest levels of fossil fuel consumption the change in
carbon levels observed in the environment was very low. How would you use the results from
our model to refute his claim?
h) Lets assume that the president calls you and asks you some advice on CO2 emission caps
to prevent global warming. You know that the CO2 in the atmosphere should stay below 4
in order to avoid major problems such as the rise of the sea level. You want to decide on
a policy to cap emissions between now and 2150. You can cap emissions, say at 10, in that
time range with the command:
fdata(6:10) = 10;
inside the function carbon. Find a value to cap emissions (i.e. adjust the number 10 above)
such that the CO2 concentration stays below 4.
In this section we learn how to solve Second Order ODEs by reducing them to a system of coupled
first order ODEs. Consider the Second Order ODE:
Let us introduce two auxiliary functions y1 (t) and y2 (t) such that
Therefore,
y20 (t) = y 00 (t).
Hence we can write our Second Order ODE as
y10 = y2
1
y20 =
F0 cos(t) y2 Ky1 .
m
Solving the above set of first order ODEs will give us the solution to our Second Order ODE. Let
us define our Second Order ODE with a function myode:
function yp = myode(t,y)
yp = [0;0];
yp(1) = y(2);
yp(2) = (F0*cos(w*t) - gamma*y(2) - k*y(1))/m;
end
50/55 CME 102 Matlab Workbook 2008-2009
The myode function takes two input arguments, scalar t (time) and column vector y (state) and
returns the output argument yp, a column vector of state derivatives. Note that other variables
such as F0, w, gamma, k, and m appear in this function. The technique of nested functions needs
to be used to make this work. We call ode45 to solve our Second Order ODE defined by myode
from t = a to t = b, where the initial conditions y(a) = y0 and y 0 (a) = y00 are given as the first and
second entries of [y0 yp0], respectively.
[t,y] = ode45(@myode,[a b],[y0 yp0]);
The first column of y contains our solution. The second column contains y 0 (t). With this approach,
it is always possible to express a system of nonlinear differential equations as a set of first order
differential equations.
Solving a System of Second Order ODEs
In this section we will learn how to reduce a system of Second Order ODEs to a system of First
Order ODEs and solve it the same way we have done before.
To do this, let us consider an example of the motion of a space probe in the gravitational field of
two bodies (such as the earth and the moon). The equations governing the motion of the spacecraft
is a system of second order differential equations.
Spacecraft
Y
Earth
Moon
X
Center of Mass
M E
We have a system as shown above. Both bodies impose a force on the spacecraft according to the
gravitational law, but the mass of the spacecraft is too small to significantly affect the motion of
the bodies. We therefore neglect the influence of the spacecraft on the two stellar bodies. Our
co-ordinate system has its origin at the center of mass of earth and moon. The governing equations
are given by
d2 x dy E(x + M ) M (x E)
+x
= 2
dt2 dt r13 r23
d2 y dx Ey M y
= 2 +y 3 3
dt2 dt r1 r2
p p
where r1 = (x + M )2 + y 2 , r2 = (xE )2 + y 2 , and E = 1 M .
The earth and moon are assumed to have circular orbits around the center of mass of the system.
To simplify the problem, we therefore consider a coordinate system which is rotating with the earth
CME 102 Matlab Workbook 2008-2009 51/55
and the moon. In that system, the earth does not move and is located at (M, 0) and the moon
is at (E, 0). The governing equations contain terms in r12 , which correspond to the gravitational
force. However, the equations also contain terms dy dx
dt and dt , which correspond to the Coriolis
force, as well as terms x and y, which correspond to the Centrifugal force.
We first need to reduce the system of second-order differential equations into a first-order system
of four equations. To do this, we define
dx dy
z1 = x, z2 = , z3 = y, and z4 = .
dt dt
In vector form, we get
z1 x
z2 x0
Z=
z3 = y .
z4 y0
Therefore,
0 0 z2
z1 x
E(z1 +M )
0
z20 x00 2z4 + z1 r13
M (Ez
r23
1)
Z = 0 = 0 =
z3 y z4
z40 y 00 2z2 + z3 Ez 3
M z3
r13 r23
p p
where r1 = (z1 + M )2 + z32 and r2 = (z1 E)2 + z32 . Now we can easily write the function for
defining our ODE as follows:
function zp = ZPrime(t,z)
zp = [0 0 0 0];
R1 = sqrt((z1+M)^2 + (z3)^2);
R2 = sqrt((z1-E)^2 + (z3)^2);
zp(1) = z2;
zp(2) = 2*z4 + z1 - E*(z1+M)/R1^3 - M*(z1-E)/R2^3;
zp(3) = z4;
zp(4) = -2*z2 + z3 - E*z3/R1^3 - M*z3/R2^3;
end
M = 0.012277,
52/55 CME 102 Matlab Workbook 2008-2009
x(0) = 1.15,
dx
(0) = 0,
dt
y(0) = 0,
dy
(0) = 0.008688.
dt
Solution:
a) function spacecraft
M = 0.012277; E = 1-M;
tspan = [0 24];
x0 = 1.15; xp0 = 0;
y0 = 0; yp0 = 0.008688;
[t,z] = ode45(@ZPrime,tspan,z0);
plot(z(:,1),z(:,3),-M,0,bo,E,0,bo)
grid on;
axis([-.8 1.2 -.8 .8]);
xlabel(x); ylabel(y);
title(The orbit in a rotating coordinate system);
text(0,0.05,Earth); text(0.9,-0.15,Moon);
function zp = ZPrime(t,z)
zp = zeros(4,1);
R1 = sqrt((z1+M)^2 + (z3)^2);
R2 = sqrt((z1-E)^2 + (z3)^2);
% M and E are defined in the spacecraft() function.
% We are using the technique of nested function.
zp(1) = z2;
zp(2) = 2*z4 + z1 - E*(z1+M)/R1^3 - M*(z1-E)/R2^3;
zp(3) = z4;
zp(4) = -2*z2 + z3 - E*z3/R1^3 - M*z3/R2^3;
end
CME 102 Matlab Workbook 2008-2009 53/55
end
The orbit in a rotating coordinate system
0.8
0.6
0.4
0.2
Earth
0
y
Moon
0.2
0.4
0.6
0.8
0.5 0 0.5 1
x
X Ground
Consider the trajectory of the bottle. We can break Newtons law of motion into two components:
the horizontal(x) and the vertical(y).
mx00 = Cd ||~v || x0
my 00 = mg Cd ||~v || y 0
where
m = mass of the bottle
54/55 CME 102 Matlab Workbook 2008-2009
Note that the friction scales according to ||~v ||2 and thus is larger when the bottle moves faster.
Suppose a bottle of mass 0.3 kg is released at t = 0 from an aircraft moving at a speed of 350 m/s
and at an altitude of y0 = 3000 m. We want to compute the time of the flight of the bottle of Coke
and where it will land on the ground. Let y = y0 and x = 0 at t = 0.
z10 x0
z2
Cd Cd
0 0 z2 2 + z 4 2 z 2
~ 0 = z2 = m ||~v ||x m
Z 0
z3 0
=
y z4
0 Cd Cd
z4 g m ||~v ||y 0 2
g m z2 + z4 z4 2
Write a function YPrime which takes t and Z as input and returns Z 0 as output. Cd , g, m are
parameters in this function. Use the technique of nested functions.
c) Write a matlab program to solve the ODE using ode45 and estimate the time of impact from
the graph of y(t).
d) Plot the trajectory of the bottle and hence find the total horizontal distance travelled by the
bottle.
e) Plot the speed of the bottle ||~v || as a function of time. What is the velocity at the point of
impact? What do you notice about the behaviour of the velocity? How can you explain this
observation?
Hint: You have to use column 2 and column 4 of the output y of ode45 for the velocities.
CME 102 Matlab Workbook 2008-2009 55/55
f) Say instead of a glass bottle, the pilot drops a can with similar weight. How does the change
in the drag coefficient affect the time of impact and the horizontal distance travelled by the
falling object? (You can try varying the drag coefficient by changing the terminal velocity.)