问题
I use R
but I am translating code from matlab to R
. I have reached a section which I cannot grok.
My research shows that the @
allows you to call a function by another name with fixed variables e.g.
g = @(b) f(a1, b, c1)
allows me to call f
only specifying b
by doing g(b)
In the code I am working with there is a function
function dN = WW(N,h,A,P,aA,aP,bA,bP)
at some point in the code it appears WW
is called, but is called with
f = @(t,N) WW(N,h,A,P,aA,aP,bA,bP)
Why I am so confused is that t,N
are mentioned nowhere else in the code....but h,A,P,aA,aP,bA,bP
are all defined prior.
does anyone recognise this structure and what might be going on?
回答1:
You are correct in your assessment of @
. @(t)
is what is known as an anonymous function. @(t)
will thus return a handle to a function that takes in one variable t
. Basically, it's a function that takes in one parameter, t
. The rest of the parameters are defined previously in your workspace.
As an example, your statement of g = @(b) f(a1, b, c1)
allows you to encapsulate this function call into another function called g
, and a1
and c1
are previously defined in your workspace. This function will thus rely on one variable that goes into the function, which is b
. As such, these parameters will remain static when you call the function g
, and you can change b
on the fly. In other words, every time you call g
, a1
and c1
will always stay the same while b
will change depending on what you put into g
(check out Lexical Scope). Obviously, should a1
and c1
change in your workspace, this behaviour will be reflected when you call g
the next time as well.
Now, with the other function call. t
is never used, but N
is! As such, N
will dynamically change when you vary it, but t
will have no effect on that function handle of f
. No matter how you vary t
, the output of f
will be the same, provided that you don't change N
!
In any case, your assessment is indeed correct.
回答2:
at some point in the code it appears
function dN = WW(N,h,A,P,aA,aP,bA,bP)
is called, but is called with
f = @(t,N) WW(N,h,A,P,aA,aP,bA,bP)
Why I am so confused is that
t,N
are mentioned nowhere else in the code....buth,A,P,aA,aP,bA,bP
are all defined prior.
That's completely ok. What happens here is that if you do
f(value_for_t, value_for_N)
it calls
WW(value_for_N,h,A,P,aA,aP,bA,bP)
(oops? t
isn't used...)
so everything which contains t
or N
is replaced or gone.
来源:https://stackoverflow.com/questions/24084281/matlab-to-r-function-calling-and