odeset - Create or modify options structure for ODE and PDE solvers - MATLAB (original) (raw)
Create or modify options structure for ODE and PDE solvers
Syntax
Description
[options](#bu2m9z6-options) = odeset([Name=Value](#namevaluepairarguments))
creates an options structure that you can pass as an argument to ODE and PDE solvers. In the structure, options
, the named options have the specified values. Any unspecified options have default values. For example,options = odeset(RelTol=1e-3)
returns an options structure with RelTol
set to 1e-3
.
[options](#bu2m9z6-options) = odeset([oldopts](#bu2m9z6-oldopts),[Name=Value](#namevaluepairarguments))
modifies an existing options structure, oldopts
, using the newly specified name-value arguments. This overwrites any old values of the specified options, and adds values for new options to the structure.
[options](#bu2m9z6-options) = odeset([oldopts](#bu2m9z6-oldopts),[newopts](#bu2m9z6-newopts))
modifies an existing options structure, oldopts
, by combining it with a new options structure, newopts
. Any new options not equal to []
overwrite the corresponding options in oldopts
.
odeset
with no input arguments displays all possible option names and their possible values. Default values are indicated with {}
, where applicable.
Examples
Create an options structure that contains values for RelTol
and AbsTol
.
options = odeset(RelTol=1e-8,AbsTol=1e-10);
Update the value of AbsTol
in the existing options structure.
options = odeset(options,AbsTol=1e-9)
options = struct with fields: AbsTol: 1.0000e-09 BDF: [] Events: [] InitialStep: [] Jacobian: [] JConstant: [] JPattern: [] Mass: [] MassSingular: [] MaxOrder: [] MaxStep: [] MinStep: [] NonNegative: [] NormControl: [] OutputFcn: [] OutputSel: [] Refine: [] RelTol: 1.0000e-08 Stats: [] Vectorized: [] MStateDependence: [] MvPattern: [] InitialSlope: []
Create two options structures.
opts_1 = odeset(RelTol=1e-8,AbsTol=1e-9,OutputFcn=@odeplot,Stats="on");
opts_2 = odeset(Mass=@(t) [t 0; 0 -t],MStateDependence="none",... MassSingular="no",OutputFcn=@odephas2);
Combine the options structures, giving preference to opts_2
. Since both structures contain different values for OutputFcn
, the value in opts_2
overrides the one in opts_1
.
opts = odeset(opts_1,opts_2)
opts = struct with fields: AbsTol: 1.0000e-09 BDF: [] Events: [] InitialStep: [] Jacobian: [] JConstant: [] JPattern: [] Mass: @(t)[t,0;0,-t] MassSingular: 'no' MaxOrder: [] MaxStep: [] MinStep: [] NonNegative: [] NormControl: [] OutputFcn: @odephas2 OutputSel: [] Refine: [] RelTol: 1.0000e-08 Stats: 'on' Vectorized: [] MStateDependence: 'none' MvPattern: [] InitialSlope: []
Input Arguments
Old options structure, specified as a structure previously created using odeset
.
Data Types: struct
New options structure, specified as a structure previously created using odeset
.
Data Types: struct
Name-Value Arguments
Specify optional pairs of arguments asName1=Value1,...,NameN=ValueN
, where Name
is the argument name and Value
is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.
Before R2021a, use commas to separate each name and value, and enclose Name
in quotes.
Example: options = odeset(AbsTol=1e-3,Reltol=1e-2,Jacobian=@J,Mass=M)
specifies thresholds for the absolute and relative error tolerances, a function that returns the Jacobian matrix, and a numeric mass matrix.
Error Control
Relative error tolerance, specified as a positive scalar. This tolerance measures the error relative to the magnitude of each solution component. Roughly speaking, it controls the number of correct digits in all solution components, except those smaller than the absolute toleranceAbsTol
.
At each step, the ODE solver estimates the local error e
in the i
th component of the solution. To be successful, the step must have acceptable error, as determined by both the relative and absolute error tolerances:
|e(i)| <= max(RelTol*abs(y(i)),AbsTol(i))
Example: opts = odeset(RelTol=1e-5,AbsTol=1e-7)
Data Types: single
| double
Absolute error tolerance, specified as a positive scalar or vector. This tolerance is a threshold below which the value of the solution becomes unimportant. If the solution |y|
is smaller thanAbsTol
, then the solver does not need to obtain any correct digits in |y|
. For this reason, the value of AbsTol
should take into account the scale of the solution components.
If AbsTol
is a vector, then it must be the same length as the solution. If AbsTol
is a scalar, then the value applies to all solution components.
At each step, the ODE solver estimates the local error e
in the i
th component of the solution. To be successful, the step must have acceptable error, as determined by both the relative and absolute error tolerances:
|e(i)| <= max(RelTol*abs(y(i)),AbsTol(i))
Example: opts = odeset(RelTol=1e-5,AbsTol=1e-7)
Data Types: single
| double
Control error relative to the norm of the solution, specified as "on"
or"off"
. When NormControl
is"on"
, the solvers control the errore
at each step using the norm of the solution rather than its absolute value:
norm(e(i)) <= max(RelTol*norm(y(i)),AbsTol(i))
Example: opts = odeset(NormControl="on")
Data Types: char
| string
Solver Output
Nonnegative solution components, specified as a scalar or vector. The scalar or vector selects which solution components must be nonnegative.
Note
NonNegative
is not available for ode23s
or ode15i
. Additionally, for ode15s
, ode23t
, and ode23tb
it is not available for problems where there is a mass matrix.
Example: opts = odeset(NonNegative=1)
specifies that the first solution component must be nonnegative.
Data Types: single
| double
Output function, specified as a function handle. The ODE solver calls the output function after each successful time step. If you call an ODE solver with no outputs, then the output function defaults to@odeplot
, which plots all of the solution components as they are computed. Otherwise, the default is[]
.
These are the built-in output functions that you can use with OutputFcn
:
Function Name | Description |
---|---|
odeplot | Plot all components of the solution vs. time |
odephas2 | 2-D phase plane plot of the first two solution components |
odephas3 | 3-D phase plane plot of the first three solution components |
odeprint | Print solution and time step |
If you write a custom output function, then it must be of the form
status = myOutputFcn(t,y,flag)
The output function must also respond appropriately to these flags:
Flag | Description |
---|---|
"init" | The solver calls myOutputFcn([tspan(1) tspan(end)],y0,"init") before beginning the integration to allow the output function to initialize. tspan andy0 are the input arguments to the ODE solver. |
[] | The solver calls status = myOutputFcn(t,y,[]) after each integration step for which output is requested. t contains points where output was generated during the step, and y is the numerical solution at the points in t. If t is a vector, then the ith column of y corresponds to the ith element of t.If length(tspan) > 2, then the output is produced at every point in tspan.If length(tspan) = 2, then the output is produced according to the Refine option.myOutputFcn must return a status of 0 or 1. If status = 1, then the solver halts integration. You can use this mechanism, for instance, to implement a Stop button. |
"done" | The solver calls myOutputFcn([],[],"done") once integration is complete to allow the output function to perform cleanup tasks. |
Data Types: function_handle
Component selection for output function, specified as a vector of indices. The vector specifies which components of the solution to pass to the output function.
Example: opts = odeset(OutputFcn=@myFcn,OutputSel=[1 3])
passes the first and third components of the solution to the output function.
Solution refinement factor, specified as a scalar. The scalar specifies a factor by which the number of output points should increase in each step.
The default value of Refine
for most solvers is1
, but ode45
uses a default value of 4
, while ode78
andode89
use a default value of8
. These solvers use a larger default value to compensate for their tendency to take large steps.
- If the refinement factor is
1
, then the solver returns solutions only at the end of each step. - If the refinement factor is
n > 1
, then the solver subdivides each step inton
smaller intervals and returns solutions at each point.
The extra values produced by the refinement factor are computed by means of continuous extension formulas. These are specialized formulas used by the ODE solvers to obtain accurate solutions between computed time steps without significant increase in computation time.
Note
Refine
does not apply when length(tspan) > 2
, or when the ODE solver returns the solution as a structure.
Example: opts = odeset(Refine=5)
increases the number of output points by a factor of five.
Solver statistics, specified as "on"
or "off"
. When"on"
, the solver displays information after completing the solution:
- The number of successful steps
- The number of failed attempts
- The number of times the ODE function was called to evaluate f(t,y)
Implicit solvers display additional information about the solution:
- The number of times that the partial derivatives matrix ∂f/∂y was formed
- The number of LU decompositions
- The number of solutions of linear systems
Example: opts = odeset(Stats="on")
Data Types: char
| string
Step Size
Suggested initial step size, specified as a positive scalar. InitialStep
sets an upper bound on the magnitude of the first step size that the solver tries.
If you do not specify an initial step size, then the solver bases the initial step size on the slope of the solution at the initial time point, tspan(1)
. If the slope of all solution components is zero, then the solver might try a step size that is too large. If you are aware that this is occurring, or if you want to be sure that the solver resolves important behavior at the beginning of the integration, then use InitialStep
to provide a suitable initial step size.
Example: opts = odeset(InitialStep=1e-3)
sets an upper bound of1e-3
on the size of the initial step.
Maximum step size, specified as a positive scalar. MaxStep
sets an upper bound on the size of any step taken by the solver. If the equation has periodic behavior, for example, then setting MaxStep
to a fraction of the period ensures that the solver does not enlarge the step so much that it steps over an area of interest.
- Do not use
MaxStep
just to obtain more output points, as it can significantly slow down the integration. Instead, use theRefine
option to compute additional points at low computational cost. - Do not use
MaxStep
to increase the accuracy of the solution. If the solution is not accurate enough, then reduce the value ofRelTol
and use the solution to determine a suitable value forAbsTol
. - Avoid using
MaxStep
to make sure the solver does not step over some behavior that occurs only once in the integration interval. If you know the time at which the behavior occurs, then break the interval into two pieces and call the solver twice. If you do not know the time at which the change occurs, try reducingRelTol
andAbsTol
. UseMaxStep
only as a last resort in this case.
Example: opts = odeset(MaxStep=1e-2)
Since R2024b
Minimum step size, specified as a positive scalar.MinStep
sets a lower bound on the size of any step taken by the solver. MinStep
must be less thanMaxStep
.
Solver steps are limited by floating-point precision regardless of the value of MinStep
.
Example: opts = odeset(MinStep=1e-10)
Event Location
Event function, specified as a function handle such as@myEventsFcn
.
Function Signature
For ODEs: The event function specified by the function handle must have the general form
[value,isterminal,direction] = myEventsFcn(t,y)
For PDEs: The event function specified by the function handle must have the general form
[value,isterminal,direction] = myEventsFcn(m,t,xmesh,umesh)
In both cases, value
,isterminal
, and direction
are vectors whose i
th element corresponds to thei
th event function:
value(i)
is the value of thei
th event function.isterminal(i) = 1
if the integration is to terminate at a zero of this event function. Otherwise, it is0
.direction(i) = 0
if all zeros are to be located (the default). A value of+1
locates only zeros where the event function is increasing, and-1
locates only zeros where the event function is decreasing.
See Parameterizing Functions to see how to pass in additional inputs to the events function.
Events Output
If you specify an events function, you can call the solver with three extra output arguments, such as
[t,y,te,ye,ie] = odeXY(odefun,tspan,y0,options)
The three additional outputs returned by the solver correspond to the detected events:
te
is a column vector of the times at which events occurred.ye
is the solution value corresponding to the event times inte
.ie
are indices into the vector returned by the events function. The values indicate which event the solver detected.
Alternatively, you can call the solver with a single output as
sol = odeXY(odefun,tspan,y0,options)
In this case, the event information is stored in the structure assol.te
, sol.ye
, andsol.ie
.
Diagnostics
The root finding mechanism employed by the ODE/PDE solver in conjunction with the event function has these limitations:
- If a terminal event occurs during the first step of the integration, then the solver registers the event as nonterminal and continues integrating.
- If more than one terminal event occurs during the first step, then only the first event registers and the solver continues integrating.
- Zeros are determined by sign crossings between steps. Therefore, zeros with an even number of crossings between steps can be missed.
If the solver steps past events, try reducingRelTol
and AbsTol
to improve accuracy. Alternatively, set MaxStep
to place an upper bound on the step size. Adjustingtspan
does not change the steps taken by the solver.
Examples
- See ODE Event Location for examples of ODE event functions that detect the bounces of a ball and orbits of celestial bodies.
- See Solve Oscillatory PDE with Event Logging for an example of a PDE event function detecting the zero-crossings of an oscillatory solution.
Data Types: function_handle
Jacobian Matrix
Jacobian matrix, specified as a matrix, cell array, or function that evaluates the Jacobian. The Jacobian is a matrix of partial derivatives of the function that defines the differential equations.
You can specify the Jacobian as a constant matrix with calculated values for ∂f∂y, or as a function that computes the matrix elements and has the general form
For the stiff ODE solvers (ode15s, ode23s, ode23t, ode23tb, and ode15i), providing information about the Jacobian matrix is critical for reliability and efficiency. If you do not provide the Jacobian, then the ODE solver approximates it numerically using finite differences.
For ode15i
only: The Jacobian
option must specify matrices for both ∂f∂y and ∂f∂y'. You can provide these matrices as a cell array of two constant matrices {∂f∂y, ∂f∂y'}, or as a function that computes the matrices and has the general form
[dfdy, dfdp] = Fjac(t,y,yp)
For very large systems where it is not feasible to provide the entire analytic Jacobian, use the JPattern
property to pass in the sparsity pattern of the Jacobian matrix. The solver uses the sparsity pattern to calculate a sparse Jacobian.
Example: opts = odeset(Jacobian=@Fjac)
specifies the functionFjac
that calculates the Jacobian matrix.
Example: opts = odeset(Jacobian=[0 1; -2 1])
specifies a constant Jacobian matrix.
Example: opts = odeset(Jacobian={A,Ap})
specifies two constant Jacobian matrices for use with ode15i
.
Data Types: single
| double
| cell
| function_handle
Jacobian sparsity pattern, specified as a sparse matrix. The sparse matrix contains1
s where there might be nonzero entries in the Jacobian. The ODE solver uses the sparsity pattern to generate a sparse Jacobian matrix numerically. Use this option to improve execution time when the ODE system is large and you cannot provide an analytic Jacobian.
For ode15i
only: Set the JPattern
option using a cell array containing two sparse matrices {dfdyPattern, dfdypPattern}
, which are the sparsity patterns for ∂f∂y and ∂f∂y'.
Note
If you specify a Jacobian matrix using Jacobian
, then the solver ignores any setting for JPattern
.
Example: opts = odeset(JPattern=S)
specifies the Jacobian sparsity pattern using sparse matrix S
.
Example: opts = odeset(JPattern={dFdy, dFdyp})
specifies two constant Jacobian sparsity patterns for use withode15i
.
Data Types: single
| double
| cell
Vectorized function toggle, specified as "off"
or "on"
. Use this option to inform the ODE solver that the function is coded so that it accepts and returns vectors for the second argument. That is,f(t,[y1 y2 y3...])
returns [f(t,y1) f(t,y2) f(t,y3) ...]
. Compared to evaluating values one at a time, this vectorization allows the solver to reduce the number of function evaluations required to compute all the columns of the Jacobian matrix, and might significantly reduce solution time. See Array vs. Matrix Operations for a description of the element-wise operators that support vectorization.
For ode15i
only: Set the Vectorized
option using a two-element cell array. Set the first element to"on"
if f(t,[y1,y2,...],yp)
returns [f(t,y1,yp), f(t,y2,yp), ...]
. Set the second element to "on"
iff(t,y,[yp1,yp2,...])
returns[f(t,y,yp1), f(t,y,yp2), ...]
. The default value of Vectorized
in this case is{"off","off"}
.
Note
If you specify a Jacobian matrix usingJacobian
, then the solver ignores a setting of"on"
forVectorized
.
Example: opts = odeset(JPattern=S,Vectorized="on")
specifies that the function is vectorized and sets the Jacobian sparsity pattern.
Example: opts = odeset(JPattern={dy,dyp},Vectorized={"on","on"})
specifies that the function is vectorized with respect to y
andyp
, and also sets the Jacobian sparsity pattern for use with ode15i
.
Data Types: char
| cell
| string
Mass Matrix and DAEs (do not apply to ode15i
)
Mass matrix, specified as a matrix or function handle. The ODE solvers can solve problems containing a mass matrix of the form M(t,y) y'=f(t,y), where M(t,y) is a mass matrix that can be full or sparse (theode23s solver can solve only equations with constant mass matrices).
- When the mass matrix is nonsingular, the equation simplifies to y'=M−1 f(t,y) and the ODE has a solution for any initial value. However, it is often more convenient and natural to express the model in terms of the mass matrix directly using M(t,y) y'=f(t,y), and avoiding the computation of the matrix inverse reduces the storage and execution time needed to solve the problem.
- When M(t,y) is a singular matrix, then the problem is a system of differential algebraic equations (DAEs). A DAE has a solution only when
y0
is consistent; that is, there exists an initial slopeyp0
such thatM(t0,y0)yp0 = f(t0,y0)
, whereyp0
is specified using theInitialSlope
option. DAEs are characterized by their differential index, or the number of derivatives required to simplify the system to an equivalent system of ODEs. For DAEs of index 1, solving an initial value problem with consistent initial conditions is much like solving an ODE. The ode15s and ode23t solvers can solve DAEs of index 1. When solving DAEs, it is advantageous to formulate the problem so that the mass matrix is a diagonal matrix (a semiexplicit DAE).
In all cases, mass matrices that are time- or state-dependent (instead of constant) require the use of additional options:
- For problems of the form M(t)y'=f(t,y), set the
MStateDependence
option to"none"
. This ensures that the solver calls the mass matrix function with a single input argument fort
. - If the mass matrix depends on
y
, then setMStateDependence
to either"weak"
(default) or"strong"
. In both cases the solver calls the mass matrix function with two inputs(t,y)
, but the"weak"
option results in implicit solvers using approximations when solving algebraic equations. - If the system contains many equations with a strongly state-dependent mass matrix M(t,y), then set
MvPattern
to a sparse matrixS
to specify the sparsity pattern.
Example: The example files fem2ode
and batonode
illustrate different uses of the mass matrix.
Data Types: single
| double
| function_handle
State dependence of mass matrix, specified as "weak"
,"strong"
, or "none"
.
- For problems of the form M(t)y'=f(t,y), set the
MStateDependence
option to"none"
. This ensures that the solver calls the mass matrix function with a single input argument fort
. - If the mass matrix depends on
y
, then setMStateDependence
to either"weak"
(default) or"strong"
. In both cases the solver calls the mass matrix function with two inputs(t,y)
, but the"weak"
option results in implicit solvers using approximations when solving algebraic equations.
Example: opts = odeset(Mass=@M,MStateDependence="none")
specifies that the mass matrix M
depends only ont
.
Data Types: char
| string
Mass matrix sparsity pattern, specified as a sparse matrix. Use this option to specify the sparsity pattern of the matrix ∂∂y[M(t,y)v]. The sparse matrix S
hasS(i,j) = 1
if for any k
, the(i,k)
component of M(t,y) depends on component j
ofy
.
Note
MvPattern
is for use byode15s
, ode23t
, andode23tb
whenMStateDependence
is"strong"
.
Example: opts = odeset(MStateDependence="strong",MvPattern=S)
Data Types: single
| double
Singular mass matrix toggle, specified as "maybe"
,"yes"
, or "no"
. The default value of "maybe"
causes the solver to test whether the problem is a DAE, by testing whether the mass matrix is singular. Avoid this check by specifying "yes"
if you know the system is a DAE, or "no"
if it is not.
Data Types: char
| string
Consistent initial slope, specified as a vector. Use this option with theode15s
and ode23t
solvers when solving DAEs. The specified vector is the initial slope y'0 such that M(t0,y0)y'0=f(t0,y0). If the specified initial conditions are not consistent, then the solver treats them as guesses, attempts to compute consistent values that are close to the guesses, and continues to solve the problem.
Data Types: single
| double
Only for ode15s
and ode15i
Maximum order of formula, specified as an integer between 1
and5
. Use this option to specify the maximum order used in the numerical differentiation formulas (NDFs) or backward differentiation formulas (BDFs) that are used by the variable-order solvers ode15s
andode15i
.
Toggle to use backward differentiation formulas (BDFs) with ode15s
, specified as "off"
or "on"
. The default numerical differentiation formulas (NDFs) are generally more efficient than BDFs, but the two are closely related.
Example: opts = odeset(BDF="on",MaxOrder=4)
enables the use of BDFs byode15s
with a maximum order of4
.
Data Types: char
| string
Output Arguments
Options structure. options
can be used as a fourth input argument to ode45
, ode23
, ode113
, ode15s
, ode23s
, ode23t
, ode23tb
, or ode15i
.
Tips
- See Summary of ODE Examples and Files for a list of ODE examples that illustrate the use of various options.
Extended Capabilities
Usage notes and limitations:
- All inputs must be constant.
Version History
Introduced before R2006a
You can specify the Jacobian and mass matrix sparsity patternsJPattern
and MvPattern
as single-precision sparse matrices. For arguments that accept function handles, such as OutputFcn
, the specified functions can now return single-precision outputs.
You can specify the minimum step size as a solver option by using theMinStep
name-value argument.