Function handles as function output
49 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
James Tursa
il 5 Mar 2013
Modificato: James Tursa
il 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).
Più risposte (1)
Azzi Abdelmalek
il 5 Mar 2013
Modificato: Azzi Abdelmalek
il 5 Mar 2013
A is v, you do not need to get A
0 Commenti
Vedere anche
Categorie
Scopri di più su Logical in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!