Using Ode 45
Using Ode 45
Using Ode 45
MATLAB's standard solver for ordinary differential equations (ODEs) is the function ode45. This
function implements a Runge-Kutta method with a variable time step for efficient computation.
ode45 is designed to handle the following general problem
dy
f(t,y) y(to) yo [1] dt
where t is the independent variable (time, position, volume) and y is a vector of dependent variables
(temperature, position, concentrations) to be found. The mathematical problem is specified when
the
The notes here apply to versions of MATLAB above 5.0 and cover the basics of using the function
ode45. For more information on this and other ODE solvers in MATLAB, see the on-line help.
Contents:
ode45 may be invoked from the command line via [t,y] = ode45(fname, tspan, y0,
opts)
where
fname name of a function Mfile, an inline function object or an anonymous function used to
evaluate the right-hand-side function in Eq. [1] at a given value of the independent variable and
dependent variable(s). If an Mfile is used, the function definition line usually has the form
and the file is stored as fname.m. The output variable (dydt) must be a vector with the same size
as y. Note that the independent variable (t here) must be included in the input argument list even if
it does not explicitly appear in the expressions used to generate dydt. The variable fname can
contain the name of the Mfile or can be a function handle generated by an inline or anonymous
function.
tspan 2-element vector defining the range of integration ([to tf]) or can be a vector of values
for which the solution is desired.
y0 vector of initial conditions for the dependent variable. There should be as many initial
conditions as there are dependent variables.
opts a MATLAB structure variable (created by odeset) that allows you to control the details of
computation (if you want to). This argument is optional and, if not provided, ode45 will use
default values (see the examples below).
t Value of the independent variable at which the solution array (y) is calculated. Note that by
default this will not be a uniformly distributed set of values.
y Values of the solution to the problem (array). Each column of y is a different dependent
variable. The size of the array is length(t)-by-length(y0)
Specific examples of using ode45 now follow. Mfiles for these examples are in the body of this
document and should also be available in the folder that contains this document. If you cannot find
these file, just let me know ([email protected]) and I’ll send them along.
dh
(t)−h h(0)ho [2] dt
Find the solution, h(t), for 0 t 3 0 if the following values for the parameters are given.
Inputflow:(t)104sin(t) 2 ho 1 Step 1: Identify f (t,y) and write a MATLAB function Mfile to
evaluate it.
f(t,y)→f(t,h)(t)−h [3] For this problem, we’ll use the Mfile approach. From the comments on
page 2, the required Mfile, named
tankfill.m, is
function dhdt = tankfill(t,h)
% eof - tankfill.m
Step2: Useode45tosolvetheproblem
The initial condition has the height at 1 for t = 0 and we want to integrate until t = 30. The following
set of commands show explicitly how the solution is put together.
In this case, we have time as the independent variable and the tank height as the (single) dependent
variable. Thus, we have
>> plot(t,h)
The "curve" is a little choppy though it is accurate to the default relative tolerance (0.001). Note that
the places where the solution is given are not uniformly spread out. See the next section for
improving appearances.
ode45 uses a variable-step-length algorithm to find the solution for a given ODE. Thus, ode45
varies the size of the step of the independent variable in order to meet the accuracy you specify at
any particular point along the solution. If ode45 can take "big" steps and still meet this accuracy, it
will do so and will therefore move quickly through regions where the solution does not "change"
greatly. In regions where the solution changes more rapidly, ode45 will take "smaller" steps.
While this strategy is good from an efficiency or speed point of view, it means that the solution
does not appear at a fixed set of values for the independent variable (as a fixed-step method would)
and sometimes the solution curves look a little ragged.
The simplest way to improve on the density of solution points is to modify the input tspan from a
2- element vector to an N-element vector via something like
>> tspan = linspace(to,tf,500)’; and use this new version in the input list to ode45.
Smoother curves can also be generated by post-processing operations such as interpolation (spline
interpolation usually works nicely). For example, if you wanted a smoother result from the solution
for the tank-fill problem, you might do the following
The interpolated curve smoothes out the rough edges caused by simply connecting the data points
(which is what plot does) and so makes the graph more appealing, in a visual sense.
Sometimes you have a rather simple expression for the function f(t,y) and it may be more trouble
than it’s worth to create an Mfile to evaluate that function. In such cases, the use of in-line functions
can simplify things. For more information on inline objects, see help inline.
Note that the order of the input arguments is explicitly specified so that when you “look” at the
object f,
>> f f=
Using inline functions
As an example of the use in in-line function, consider the following version of the tank-fill problem
presented above:
Inline function:
f(t,y) = 10+4*sin(t)-2*sqrt(y)
As long as f(t,y) is simple (e.g., it does not require extra parameters or too many steps to evaluate),
it’s probably pretty easy to use this approach.
Chemical-kinetics problems often lead to sets of coupled, first-order ODEs. For example, consider
the reaction network
A↔B→C [4] Assuming a first-order reaction-rate expression for each transformation, material
balances for each
dA
−k1Ak2B dt
dB
k1 A −k2 B −k3 B dt
dC
k3B dt
[5]
with the initial conditions, A(0) Ao ,B(0) Bo ,C(0) Co . Since the equations are coupled, you
cannot solve each one separately and so must solve them simultaneously.
The system in Eq. [5] can be put in the standard form for ode45 (Eq. [1]) by defining the vectors y,
yo and f as
⎢ ⎥ ⎢ ⎥ ⎢ ⎥
⎡A⎤⎡Ao⎤⎡−k1y1 k2y2 ⎤y
⎢B ⎥y(0)y ⎢B ⎥f(t,y) ⎢ky −(k k )y ⎥
[6]
oo 11232 ⎢C⎥⎢C⎥⎢ky⎥
⎣⎦⎣o⎦⎣32 ⎦
Solving the system represented by Eq. [6] is a simple extension of what was done for solving a
single
k15 k22 k31 Ao1 BoCo0 Step 1: Write a function Mfile to evaluate the right-hand-side
expression
The primary difference here, compared to the single-equation case, is that the input variable y will
be a vector. The first element of y represents the concentration of species A at a time t, and the
second and third elements representing the concentrations of species B and C, respectively, at the
same time, t. This ordering of variables is defined by Eq. [6]. There is no "right" order to the
variables but whatever order you do choose, use it consistently. We'll call the Mfile react.m. It
looks like this:
dydt = zeros(size(y));
% Parameters - reaction-rate constants k1=5; k2=2; k3=1;
A = y(1); We'll be explicit about it here though you can do B = y(2); the calculations
directly with the y-values.
C = y(3);
% eof - react.m
Note that the input arguments must be t and y (in that order) even though t is not explicitly used
in the
function.
Step2: Useode45tosolvetheproblem
No time interval is given so we'll pick one (0 to 4) and see what the solution looks like. If a longer
or shorter interval is needed, we can simply re-execute the function with a new value for the ending
time. Following the outline for the single-equation problem, the call to ode45 is,
variable y0 prior to the call to ode45 and used that variable as an input.
Take a moment to look at the outputs. The number of points at which the solution is known is
>> length(t)
Also consider the shape of the output variable y:
>> size(y)
If you want to see the time-course of all species, use the command
>> plot(t,y)
The blue line will be the first column of y (species A). The green and red lines will be the second
and
If you wanted to look at only one species (for example, species B), you would give the command
>> plot(t,y(:,2))
since the second column of y holds the information on species B.
You can also use an inline function in this problem. The key to this use is to create the appropriate
expression. Here’s one version:
Anonymous functions or the Mfile approach are probably more useful here.
ode45 is set up to handle only first-order equations and so a method is needed to convert this
second- order equation into one (or more) first-order equations which are equivalent. The
conversion is accomplished through a technique called "reduction of order". We'll illustrate the
solution for the particular set of conditions
c 5 2 y(0) 1 v(0) 0 g(t) sin(t) Step1: Define the components of a vector p [ p p ]T as
follows:
oo
12
p1 y p2 y ̇
[8]
Using the given differential equation, we can write a system of first-order equations as
p ̇ 1 y ̇ p 2
p ̇2 y ̇ ̇ 2y [9]
̇ g(t)−cy −
g(t)−cp2 −2p1
In writing the expression for the second component, we've used the governing ODE (Eq. [7]).
⎢ ⎥ ⎢
d p d ⎡p 1 ⎤ ⎡p 2 ⎤ ⎡f 1 ( t , p ) ⎤ dt dt ⎣p ⎦ ⎣g(t)−cp
p ̇ f ( t , p )
⎥ ⎢ ⎥
−2p ⎦ ⎣f (t,p) ⎦
[10]
[11]
2212
⎢ ⎥ ⎢ ⎥ ⎢ ⎥
⎡p (0)⎤ ⎡y(0)⎤ ⎡yo⎤o ⎣p (0) ⎦ ⎣y ̇(0) ⎦ ⎣v ⎦
p(0)p 1
The Mfile for the RHS function for this problem will be called spring.m. Here it is: function
pdot = spring(t,p)
% eof - spring.m
The call to ode45 is, for a solution interval of 0 to 20,
2o Step5: Applyode45tosolvethesystemofequations
definition of p in the first step, Eq. [8]). Hence, you would give the command >>
plot(t,p(:,1))
An interesting plot for these sorts of problems is the phase-plane plot, a plot of the velocity of the
mass versus its position. This plot is easily created from your solution via
>> plot(p(:,1),p(:,2))
To use ode45 to integrate an Nth-order ODE, you simply continue the process outlined in the
section on integrating a 2nd-order ODE. The first element of the vector p is set to the dependent
variable and then subsequent elements are defined as the derivatives of the dependent variable up to
one less than the order
of the equation. Finally, the initial conditions are collected into one vector to give the format
presented in Eq. [1].
dx
⎢ ⎥⎢ ⎥
p −(bpcpdpep)/a ⎣4⎦⎣4321⎦
⎤⎢2⎥⎢3 ⎥
⎡p1⎤⎡
⎢ ⎥⎢ ⎥
d p p
p2
dt⎢p3⎥⎢p4 ⎥
[13]
which, along with an appropriate set of initial conditions would complete the set-up for ode45.
In all the examples so far, the parameter values were given specific variables in the Mfile or in-line
object used to evaluate the RHS function (the model of the system). This is fine for one-shot cases
and in instances where you don't anticipate a desire to change the parameters. However, this
situation is not fine where you want to be able to change the parameters (e.g., change the damping
coefficient in order to see the result in a phase-plane plot). One approach to changing parameters is
to simply edit the file every time you want to make a change. While having the advantage of
simplicity, this approach suffers from inflexibility, especially as the number of parameters and as
the frequency of the changes increase. To get other parameters into the function, you need to use an
expanded version of the syntax for ode45, one that allows “other” information to be provided to the
derivative function when ode45 uses that function. This is most easily seen by an example (and by
reading the on-line help on ode45).
Step 1: Write the Mfile for the RHS function so that it allows more input variables. The parameter
list starts after the dependent variable and after a required input called flag.
For this example, we will re-write spring.m so that c and w are given their values via the
function definition line. The altered Mfile is
Step 2: Write a driver script that implements your logic and allows you to set values of the
parameters for the problem.
plot(p(:,1),p(:,2))
title('Phase-plane plot of results')
xlabel('position')
ylabel('velocity')
end
% eos - dospring.m
Note the additions to the call to ode45. First, a placeholder for the “options” input is inserted (an
empty array) so that “default” options are used. Then, the parameters for the model are provided in
the order that they appear in the definition line of the RHS function.
Try the script out and modify it (e.g., you could add the frequency and/or amplitude of the forcing
function as something to be changed).
In evolving the way in which functions can be created and manipulated, MATLAB has developed
the idea of a function handle. When you created the in-line function in a previous portion of this
tutorial, the output of the function inline was a function handle. You didn’t really need to know
what a function handle is. Rather, you had a way to create a function handle (inline) and had a
function that could work with a function handle as an input (ode45).
Using anonymous functions
Bucknell University Using ODE45 10
Let’s change the tank-fill problem computation to include the ability to change the parameters (t)
and in Eq. 2. The parameter (t) is a function of time (it describes some time-dependent input to
the tank)
while the parameter is a scalar (it characterizes the geometry of the output valve of the tank).
These are two different types of parameters for sure but you’d like to study this problem by varying
both. How
Start with the punch line. You’d like to write the following command:
>> [t,h] = ode45(rhsfun,[0 tf],h0); (solve the problem)
The goal is to make sure that the object rhsfun (which will be a function handle) has everything
needed to evaluate the right-hand side function for the ODE.
There are several ways one might make this work. I’m going to approach it simply yet try and make
it clear where you might make improvements of extensions – or apply the method to a problem of
your own.
As a first example, assume that the input function is a relatively simple expression, on for which an
inline function might be a good match. Thus, create (t) as before and assign a value to :
a = inline('10 + 4*sin(t)','t');
b = 2;
Then create a function handle for the right-hand side function using the anonymous-function syntax
The syntax here is not the best (in my humble opinion) but you can get used to it – especially when
it works for you. To understand what’s going on here, let’s break this line down. The @ operator (in
this context) is the anonymous-function operator that creates a function handle (rhsfun) from the
information that it finds to its right. Hence, you should read the line generically as
The essential variables (t and h here) are enclosed in parentheses and are the variables in the
expression that the function that uses this object (ode45 in this case) must provide in order to
evaluate the expression (take a moment to let that sink in). The expression that follows is any
MATLAB expression that was valid at the time the handle was created (hence the need to define
the inline function a before the anonymous function was defined).
The function handle that is created can then be used according to the syntax of the essential variable
list. For example,
>> rhsfun(1,2)
ans =
10.5375
Note that all the details of how the inputs 1 and 2 are used within the handle are disguised. You
just need to provide them and the original definition of the expression (contained in the object
rhsfun) does the work of sorting out how to do the evaluation.
>> tf = 30;
>> h0 = 1;
>> a = inline('10 + 4*sin(t)','t');
>> b = 2;
>> rhsfun = @(t,h) (a(t) - b*sqrt(h));
>> [t,h] = ode45(rhsfun,[0 tf],h0);
>> plot(t,h)
with more complex characteristics than just h . No problem – you are still in business. Assume that
the RHS function could be computed by an Mfile you wrote that has the definition line
function a = tankfun(t,h,p1,p2)
In your function, p1 and p2 are parameters you set to make the function do what it needs to do
(and that’s up to you and your function). Then, an anonymous function will let you use your Mfile
in the same way that the inline function was used previously. To repeat the example from above,
>> tf = 30;
>> h0 = 1;
>> p1 = 2; p2 = 1;
>> rhsfun = @(t,h) tankfun(t,h,p1,p2);
>> [t,h] = ode45(rhsfun,[0 tf],h0);
Note that as long as all variables used in the expression (beyond those in the essential variable list)
are valid when the line defining rhsfun executes, you have successfully “captured” the expression
for the right-hand side in an easy-to-evaluate version, rhsfun(t,h).
Variations on this theme abound. What you do depends on the nature of the problem and the
number of times you will use the model. Just be sure to follow the rule that the expression contained
in the anonymous function should be valid at the time of the creation of the function handle.
ode45 was written to solve initial-value problems (IVPs). For example, the function cannot be
used to solve the following problem (derived from a model of heat-transfer in a metal rod):
d 2y dy
−y 0 y(0) 1 0 [14] dx2 dx x1
since the value of the derivative at x = 0 is not specified (it is known at x = 1, though). Equation
[14] is a boundary-value problem (BVP) and is common in models based on transport phenomena
(heat transfer,
All is not lost because one way to solve a BVP is to pretend it is an IVP. To make up for the lack of
knowledge of the derivative at the initial point, you can guess a value, do the integration and then
check yourself by seeing how close you are to meeting the conditions at the other end of the
interval. When you have guessed the right starting values, you have the solution to the problem.
This approach is sometimes
Integrating a second-order boundary-value problem (BVP)
called the "shooting method" by analogy to the ballistics problem of landing an artillery shell on a
target by specifying only it's set-up (powder charge and angle of the barrel).
[15]
21
where v has been used to represent the (unknown) value of the derivative at x = 0. The Mfile used to
evaluate the RHS is as follows
function dpdx = hotrod(x,p)
% Hot-rod problem illustrating the shooting method
dpdx = zeros(size(p));
dpdx(1) = p(2);
dpdx(2) = p(1);
% eof - hotrod.m
The problem will be iterative so it's not likely that the first guess will be right. From the physics of
the problem, the end of the rod (at x = 1) will be colder than the place we are starting from (x = 0)
and so we'll guess a negative value for the initial slope.
>> v = -1;
>> [x,p] = ode45('hotrod',[0 1],[1 v]);
The value of the derivative at x = 1 is the last value in the second column of p (why?). Thus, we
can check the accuracy of the first guess via
>> p(end,2)
which I found to be -0.3679. That’s too low (it should be zero). Step 3: Iterate until the boundary
condition at x = 1 is met
You can use brute force here if you have only one problem or you could finesse it by hooking the
whole thinguptofzeroandhavefzerodotheguessing. Herearemybrute-forceresults:
Value of v -1.0 -0.5
-0.75 -0.76
The trend is obvious and so the initial slope is around -0.76 (the exact value is -tanh(1) = -0.7611...).
Using fzero would be a good alternative if this problem were to be solved many times over.
If BVP’s are a serious part of your computational problem, you should have a look at bvp4c.
The input opts is a MATLAB structure variable that con be used to control the performance of the
various ODE-solvers in MATLAB. The most common option that you’ll likely want to alter is the
accuracy to which solutions are computed. To make this process easy, a pair of functions are
available – odeset for creating and changing options and odeget for displaying information on
options. To see what the current settings are, try the command
>> odeset
Default values for any setting are denoted by the braces, {}.
MATLAB uses two accuracy measures for solving ODEs – the relative tolerance (RelTol in
opts) and the absolute tolerance (AbsTol in opts). Each step in the integration is taken so that it
satisfies the condition
where the subscript k ranges over all the components of the solution vector at time step j. To alter
the default settings, use commands such as
Information on the settings for the other options is available in the on-line help.
variable order method that may be able to improve over what ode45 does.
Setting options in ode45
• If ode45 is taking too long to compute a solution, your problem may be “stiff” (i.e., it involves a
system with a wide range of time constants). Try the function ode15s.
dy
M f(t,y) dt
the on-line function reference (available through the command doc) on any of the solvers noted
above.