Function handles as function output

44 visualizaciones (últimos 30 días)
yosey
yosey el 5 de Mzo. de 2013
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?

Respuesta aceptada

James Tursa
James Tursa el 5 de Mzo. de 2013
Editada: James Tursa el 5 de Mzo. de 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).
  1 comentario
yosey
yosey el 5 de Mzo. de 2013
Thank you. I falsely thought f looks for its variables when getting evaluated.

Iniciar sesión para comentar.

Más respuestas (1)

Azzi Abdelmalek
Azzi Abdelmalek el 5 de Mzo. de 2013
Editada: Azzi Abdelmalek el 5 de Mzo. de 2013
A is v, you do not need to get A

Categorías

Más información sobre Logical en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by