Function handles as function output

44 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by