Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous Functions calling themselves in MATLAB

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?

like image 978
Andrew Avatar asked Jun 26 '12 18:06

Andrew


1 Answers

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
>> 
like image 118
Jonas Avatar answered Oct 24 '22 07:10

Jonas