As an experiment (and because I'm generating anonymous functions off of user data) I ran the following MATLAB code:
h = @(x) x * x
h = @(x) x * x
h(3)
ans = 9
h = @(x) h(x) + 1
h = @(x)h(x)+1
h(3)
ans = 10
Basically, I made an anonymous function call itself. Instead of acting recursively, MATLAB remembered the old function definition. However, the workspace doesn't show it as one of the variables, and the handle doesn't seem to know it either.
Will the old function be stored behind the scenes as long as I keep the new one? Are there any "gotchas" with this kind of construction?
An anonymous function remembers the relevant part of the workspace at the time of definition, and makes a copy of it. Thus, if you include a variable in the definition of the anonymous function, and change that variable later, it will keep the old value inside the anonymous function.
>> a=1;
>> h=@(x)x+a %# define an anonymous function
h =
@(x)x+a
>> h(1)
ans =
2
>> a=2 %# change the variable
a =
2
>> h(1)
ans =
2 %# the anonymous function does not change
>> g = @()length(whos)
g =
@()length(whos)
>> g()
ans =
0 %# the workspace copy of the anonymous function is empty
>> g = @()length(whos)+a
g =
@()length(whos)+a
>> g()
ans =
3 %# now, there is something in the workspace (a is 2)
>> g = @()length(whos)+a*0
g =
@()length(whos)+a*0
>> g()
ans =
1 %# matlab doesn't care whether it is necessary to remember the variable
>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With