When does anonymous function capture variables in scope? Is it always capture by value?
Afficher commentaires plus anciens
When does anonymous function capture variables in scope?
For example, if a file helperFunction1.m has
function A=helperFunction1(a)
A={1,2};
A{end+1}=a;
end
and in Matlab's main workspace, we make
a={1,2};
func=@()helperFunction(a);
We know that a is passed by value. So the local copy of helperFunction retains a copy of a. And even if we set a{1}=3. Outputs of func() doesn't change.
What if we change helperFunction1.m? Such as by modifying the definition of its local A after the creation of func. Earlier func received a local copy of helperFunction.m right?
Do anonymous functions always capture everything in-scope at the time of their creation?
If the whole sequence of commands were in a function and helperFunction1 had been a nested function, does the anonymous function func capture all shared variables by reference?
Also if anonymous functions do always capture everything in-scope at the time of their creation, do I need to worry about their computational efficiency? Do Matlab tell apart what variables are referenced in the definition of the anonymous function being created and only capture those?
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Whos dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!