Spooky behavior with anonymous functions
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Andrew Liu
am 12 Mär. 2021
Kommentiert: Andrew Liu
am 15 Mär. 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?
0 Kommentare
Akzeptierte Antwort
Steven Lord
am 12 Mär. 2021
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.)
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Function Creation finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!