Function handles as function output

44 ビュー (過去 30 日間)
yosey
yosey 2013 年 3 月 5 日
function main
f = test(pi);
f(1)
end
function f = test(v)
A = v;
f = @(x) A*x;
end
In the above code, how is A saved? When f(1) gets evaluated in main-fcn, where does A come from? Is it saved in f or grabed from test workspace or something else?

採用された回答

James Tursa
James Tursa 2013 年 3 月 5 日
編集済み: James Tursa 2013 年 3 月 5 日
When you create an anonymous function handle, all variables that are not part of the argument list (e.g., A in your case) are regarded as constants. Shared data copies of them are made at the time you create the function handle and actually stored inside the function handle itself. They retain their value and use up memory even if you change the source of the "constant" later on in your code. E.g., if you had done this:
A = v;
f = @(x) A*x; % could have done f = @(x) v*x; and got same result
A = 2*v;
the last line has no effect on the function handle f. Note that if A happens to be a very large variable, its memory effectively gets "locked up" inside f and can only be cleared by clearing (or re-defining) f. E.g., in the above code snippet, the 2nd line will put a shared data copy of A inside of f. The 3rd line will cause this shared data copy to essentially become a deep data copy (it gets unshared with A at that point).
  1 件のコメント
yosey
yosey 2013 年 3 月 5 日
Thank you. I falsely thought f looks for its variables when getting evaluated.

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

その他の回答 (1 件)

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 3 月 5 日
編集済み: Azzi Abdelmalek 2013 年 3 月 5 日
A is v, you do not need to get A

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by