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!