Pass 'function handle' to another 'function handle'?

조회 수: 7 (최근 30일)
Payjay
Payjay 2017년 5월 19일
댓글: Steven Lord 2017년 5월 19일
hello there, I have a function handle, for example: f = @(x) x.^2 and this I want to put within another function handle, to integrate the new function, so smth like this I would like to have:
int(@(x) 5*log(x).*f)
, where f is the function above. Is this possible? Greets and thanks!

채택된 답변

Star Strider
Star Strider 2017년 5월 19일
It is definitely possible. You need to change your code a bit first:
int_fcn = @(x,fcn) 5*log(x).*fcn(x);
f = @(x) x.^2;
x = 10;
Result = int_fcn(x, f)
Result =
1.1513e+003
  댓글 수: 5
James Tursa
James Tursa 2017년 5월 19일
편집: James Tursa 2017년 5월 19일
One needs to be very careful when chaining function handles together this way. Remember, all of the non-argument entities in a function handle are snapshots of the workspace at the time of the function handle creation. They are not updated in the "top-level" function handle if you try to change any of these entities later on. E.g.,
>> func1 = @(x) x.^2;
>> func2 = @(x) func1(x) + x;
>> func2(3)
ans =
12
>> func1 = @(x) x.^3;
>> func2(3)
ans =
12
Clearly, the func1 that func2 is using is a snapshot of func1 that existed at the time of func2 creation. The fact that you subsequently changed func1 later on in the code does nothing to change the func1 that is in func2 ... that is still the old func1. Bottom line is if you change any of the "non-argument" entities, you need to recreate all of the function handles that depend on them in order for the changes to have an effect. Continuing the example above:
>> func2 = @(x) func1(x) + x;
>> func2(3)
ans =
30
By recreating the function handle that depended on func1, we now get consistent results with the current definition of func1.
(Technically, what happens is that shared-data copies of the non-argument entities are created and physically stored in the background as part of the function handle itself. Any subsequent workspace changes to these variables simply causes the function handle copies to become unshared and have no further connection to the workspace)
Steven Lord
Steven Lord 2017년 5월 19일
That is true. There is a trade-off. If you want to be able to use a different function handle func1 inside your function handle func2, it should accept func1 as an input argument as Star Strider wrote. If you don't want to have to specify func1 as an input argument, you lose the flexibility of modifying what func2 calls at runtime (without completely re-creating func2) as in my example and James's example.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Function Handles에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by