Recursive definition of anonymous function
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Zaikun Zhang
le 6 Mai 2020
Modifié(e) : Zaikun Zhang
le 7 Mai 2020
(Note that the mathematics in this question is hypothetical and illustrative.)
Suppose that I am writing a function "foo" to minimize any given objective function "fun", and "fun" is passed to "foo" by a function handle. Assume that, in "foo", some how, I decide that exp(fun(x)) is easier to minimize, so I do something like this:
y = function foo(fun, ...)
fun = @(x) exp(fun(x));
y = minimize(fun, ...);
end
where "minimize" is a hypothetical function that performs minimization, and "..." represents some other inputs. Assume that function "minimize" does not call function "foo" in any way.
Note that the definition fun = @(x) exp(fun(x)) seems recursive. I know that I can use a name other than "fun" for @(x) exp(fun(x)). However, suppose that I do need to use the same name, would this cause any problem?
Thank you very much!
0 commentaires
Réponse acceptée
James Tursa
le 6 Mai 2020
Modifié(e) : James Tursa
le 6 Mai 2020
@(x) STUFF
Takes a snapshot of all of the workspace variables used in STUFF in order to create the function handle. It doesn't matter if you change those variables used in STUFF later in your code ... the function handle always refers to its saved snapshots of those variables that existed at the time the function handle was created.
I don't have MATLAB handy at the moment, but I don't see any recursion here. The fun in STUFF is a snapshot of the incoming argument. Subsequently changing fun with the assignment doesn't change the snapshot already in the function handle. I will go check this ...
EDIT
Yes, this is how it works. E.g.,
>> fun = @(x)sin(x)
fun =
function_handle with value:
@(x)sin(x)
>> fun = @(x)exp(fun(x))
fun =
function_handle with value:
@(x)exp(fun(x))
>> fun(pi)
ans =
1.0000
>> exp(sin(pi))
ans =
1.0000
>> fun(pi/2)
ans =
2.7183
>> exp(sin(pi/2))
ans =
2.7183
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Historical Contests dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!