Handles: How do They Work?
조회 수: 9 (최근 30일)
이전 댓글 표시
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
채택된 답변
Richard Brown
2012년 4월 12일
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.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Ordinary Differential Equations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!