Passing a strange function handle to MATLAB ode solvers - What does this code mean?
I know how to use ode15s or other ode solver in MATLAB, what I'm not sure about, is this code(from CellML) that seems vague to me:
[VOI, STATES] = ode15s(@(VOI, STATES)computeRates(VOI, STATES, CONSTANTS), tspan, INIT_STATES, options);
More specifilcly, what is the meaning of the following (?):
@(VOI, STATES)computeRates(VOI, STATES, CONSTANTS)
The header of the function, "computeRates", is the following:
function [RATES, ALGEBRAIC] = computeRates(t, STATES, CONSTANTS)
I know "@computeRates" meanse the handle of the function, but what is the meaning of
@(VOI, STATES)computeRates(VOI, STATES, CONSTANTS)
Why has it put (VOI, STATES) between @ and "c开发者_C百科omputeRates" ?
By the way, According the MATLAB help, if we want to integrate of the following function:
function dy = rigid(t,y)
dy = zeros(3,1); % a column vector
dy(1) = y(2) * y(3);
dy(2) = -y(1) * y(3);
dy(3) = -0.51 * y(1) * y(2);
we only need to write:
options = odeset('RelTol',1e-4,'AbsTol',[1e-4 1e-4 1e-5]);
[T,Y] = ode45(@rigid,[0 12],[0 1 1],options)
As R. M. correctly points out, what you are seeing used in that code is an anonymous function. Creating one is done in the following way:
fhandle = @(arglist) expr
Where arglist
is a list of input arguments that are used in the computation of the function expression expr
.
What you may be confused about is why the code requires that an anonymous function be created instead of just using a function handle for an existing function. The MATLAB solver routines like ode15s
and ode45
will only pass two inputs to the function handle passed to them: a scalar t
and a column vector y
. If you have a situation where you want more parameters to be passed to the function to define its behavior, you have to supply the function with those parameters in other ways as described in the documentation for parameterizing functions.
Anonymous functions are one way to do this. In your example, you can see that the function computeRates
takes a third argument CONSTANTS
that supplies the function with extra parameters. When the anonymous function is made, this third input is frozen at the value(s) it contained at that moment. The anonymous function therefore acts as a wrapper that makes a three-input function behave like a two-input function so that it can be used by the solver routines, supplying the wrapped function with the extra inputs it needs that the solver routines can't pass to it.
Those are called anonymous functions, and let you create short, nifty functions on the fly without having to create a separate m
file. The two variables between the parentheses after the @
symbol are the inputs to the function. What follows it is the definition of the function. For example,
f=@(x,y)x+y;%# define an anonymous function to add the two inputs
f(2,3)
ans =
5
精彩评论