Spooky behavior with anonymous functions

1 回表示 (過去 30 日間)
Andrew Liu
Andrew Liu 2021 年 3 月 12 日
コメント済み: Andrew Liu 2021 年 3 月 15 日
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?

採用された回答

Steven Lord
Steven Lord 2021 年 3 月 12 日
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 件のコメント
Andrew Liu
Andrew Liu 2021 年 3 月 15 日
Thank you so much! This was exactly what I needed.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeFunction Creation についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by