3

I noticed anonymous functions in MATLAB can be used without specifying all the needed variables within - however, these don't seem updated at 'runtime' (if I use that term correctly):

a=1;
myfx = @(t) a+t; % a is 1 at this point, the function simply adds 't' to a
a=2;
myfx(1) % a in the base workspace is now 2, yet the function seemingly computes 1+1

ans =

     2

Can someone explain what goes on 'under the hood' (i.e. MATLAB-internally) here? It seems unintuitive to me and I imagine this may cause some common pitfalls, that should be taken into consideration.

rahnema1
  • 15,264
  • 3
  • 15
  • 27
user2305193
  • 2,079
  • 18
  • 39
  • Not asking for extreme detail here, just to get a better intuition of how to think about it – user2305193 Sep 30 '20 at 12:34
  • 2
    Short answer is that everything (except handle objects) is passed by value. – rahnema1 Sep 30 '20 at 12:38
  • 2
    The variable inside a function handle (like `myfx`) are persistent, they are stored inside the function handle, so you can even clear all the external variable and `myfx(1)` will still output `2`. – obchardon Sep 30 '20 at 12:39
  • 4
    Does this answer your question? [Force evaluation of variables in MATLAB anonymous function](https://stackoverflow.com/questions/26808668/force-evaluation-of-variables-in-matlab-anonymous-function). Not an exact dupe, but I think it answers your question (i.e. that it's a closure). – Andras Deak -- Слава Україні Sep 30 '20 at 12:42
  • 2
    @AndrasDeak I wish I had more explanations about e.g. how the memory is handled (e.g. if you use a large struct, is it just copied into memory and left there as-is?) but the answers there provide plenty of information, thank you – user2305193 Sep 30 '20 at 13:02
  • 1
    Looking at system RAM usage after each of the following commands, `a.a = rand(10000); f = @(t) a.a*t; a.a = rand(10000);` it looks like a copy of the data is made only when `a.a` is updated. – rinkert Sep 30 '20 at 13:11
  • thank you (everyone) for all the kind answers and patience. Follow up question: I'm assuming there is no sensible way to modify the variables within a defined anonymous function, right? – user2305193 Sep 30 '20 at 13:20
  • 2
    You should make them input arguments to your function. Or write a regular function with global variables (not recommended) or create a custom class where these variables are properties of the class. – Cris Luengo Sep 30 '20 at 13:22
  • 1
    Only objects of [handle classes](https://www.mathworks.com/help/matlab/handle-classes.html) can be modified. But in general MATLAB objects have value semantics. – rahnema1 Sep 30 '20 at 13:44

0 Answers0