Spooky behavior with anonymous functions
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Steven Lord
2021-3-12
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.)
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Function Creation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!