Clear Filters
Clear Filters

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

4 views (last 30 days)
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!

Accepted Answer

Star Strider
Star Strider on 19 May 2017
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 Comments
James Tursa
James Tursa on 19 May 2017
Edited: James Tursa on 19 May 2017
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 on 19 May 2017
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Function Creation in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!