Spooky behavior with anonymous functions

1 visualización (últimos 30 días)
Andrew Liu
Andrew Liu el 12 de Mzo. de 2021
Comentada: Andrew Liu el 15 de Mzo. de 2021
I noticed some useful but freaky behavior with anonymous functions and would like to understand the low-level details a bit better so I use this functionality without constant paranoia that it will blow up in my face. The behavior is easier to explain by example:
F = @(x)x+1;
for k = 1:5,F = @(x)F(x)+1;end
F(1)
% ans = 7
So it looks like MATLAB is retaining the definition of each instance of F *somewhere*. I can even save F as a mat file, and, upon reloading, F will retain this definition. Is there any way to peek into this "somewhere"? One use case is where I have a class with function handles as properties, and I want to composite those functions via overloaded arithmetic operations:
myObj1.F = @(x)x+1;
myObj2.F = @(x)x-1;
myObj3 = myObj1+myObj2; %where myObj3.F = @(x)x+1-1 or something like that
but myObj3.F will actually be something like @(x)myObj1.F(x)+myObj2.F(x)... so what happens if I clear myObj1 and/or myObj2? If someone else is examining myObj3, how could they tell what F is?
tl;dr: When nesting anonymous functions, if the variable instantiated with the anonymous function is overwritten or "cleared," the definition still seems to exist somewhere. How can a user view it?

Respuesta aceptada

Steven Lord
Steven Lord el 12 de Mzo. de 2021
See the "Variables in the Expression" section on this documentation page.
If you want to see what information an anonymous function "remembers" for debugging purposes only you can do so using the functions function. Do not attempt to use this to try to change the anonymous function (it won't work) or as part of how you use anonymous functions in the normal operation of your program (as per the Note on the functions documentation page.)
  1 comentario
Andrew Liu
Andrew Liu el 15 de Mzo. de 2021
Thank you so much! This was exactly what I needed.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

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

Etiquetas

Productos


Versión

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by