Handles: How do They Work?
3 views (last 30 days)
Show older comments
Hey all,
I'm trying to create an ODE function which measures the abundance of L and G. My problem is getting other non-variable parameters into the darn thing. I think that I can accomplish this with the use of handles, but I can't for the life of me figure out how to set up and call them.
This is the function I run...
function [g]=IFFL_TC(t0,t1,t2,A0,A1,I,Smax,Smin,EffG,dl,dg,L,G)
x = [L,G];
P = [t1,t2,A0,A1,I,Smax,Smin,EffG,dl,dg];
Param = @P; % This is where it all gets a little hazy...
[t,x] = ode45('IFFL_TC_eqns',[0 t0],x);
%%Plus more stuff that works fine
IFFL_TC_eqns is a system of 2 ODEs that spits out L and G. What I can't figure out how to pack all the necessary parameters into P and then unpack them from within IFFL_TC_eqns. I'm pretty sure it's simple, but the syntax is killing me.
Thanks in advance,
-DM
0 Comments
Accepted Answer
Richard Brown
on 12 Apr 2012
The easiest way to do this is to define a constructor function that passes out a handle to be used in the ode solver by using nested functions. For example, you've got a code that needs parameters a and b to evaluate the derivative. This is basically what you've got, but yours has heaps more parameters, and no explicit t dependence.
function dy = myfunc(t, y, a, b)
dy = a*y + b*y.^2;
end
One way to do it is to create an anonymous function
a = 1;
b = 2;
f = @(t,y) myfunc(t, y, a, b);
But probably nicer if you've got a bigger problem is to do it like this:
function hf = create_ode_fun(a, b)
% a and b are available in this scope - nested funs can see them
hf = @myfun;
function dy = myfun(t, y)
dy = a*y + b*y.^2
end
end
You'd then call it like this
hf = create_ode_fun(1, 2);
ode45(hf, blah, blah, blah)
Performance-wise both methods seem to be reasonably similar, the nested one may be slightly faster. Last time I tested this I didn't see a huge difference.
More Answers (0)
See Also
Categories
Find more on Ordinary Differential Equations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!