Recursive definition of anonymous function

6 次查看(过去 30 天)
(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!

采纳的回答

James Tursa
James Tursa 2020-5-6
编辑:James Tursa 2020-5-6
@(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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Just for fun 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by