필터 지우기
필터 지우기

Recursive definition of anonymous function

조회 수: 3 (최근 30일)
Zaikun Zhang
Zaikun Zhang 2020년 5월 6일
편집: Zaikun Zhang 2020년 5월 7일
(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
  댓글 수: 1
Zaikun Zhang
Zaikun Zhang 2020년 5월 6일
Thank you very much for the clearification.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Historical Contests에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by