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

6 visualizaciones (últimos 30 días)
Payjay
Payjay el 19 de Mayo de 2017
Comentada: Steven Lord el 19 de Mayo de 2017
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!

Respuesta aceptada

Star Strider
Star Strider el 19 de Mayo de 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 comentarios
James Tursa
James Tursa el 19 de Mayo de 2017
Editada: James Tursa el 19 de Mayo de 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 el 19 de Mayo de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Function Handles en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by