Function handles as function output
36 views (last 30 days)
Show older comments
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?
0 Comments
Accepted Answer
James Tursa
on 5 Mar 2013
Edited: James Tursa
on 5 Mar 2013
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).
More Answers (1)
Azzi Abdelmalek
on 5 Mar 2013
Edited: Azzi Abdelmalek
on 5 Mar 2013
A is v, you do not need to get A
0 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!