Andrew Tomazos
Andrew Tomazos

Reputation: 68648

Octave/MATLAB: Variable Scopes and Name Lookup?

So I have a cell array of vectors X:

octave:149> X
X = 
{
  [1,1] =

      1   17   20

  [2,1] =

      5   20   22   27

  [3,1] =

      2   17   18   21

}

I create an empty vector Y:

octave:150> Y = []
Y = [](0x0)

I then call an anonymous function on each value of X with "Y = unique([Y x])":

octave:151> cellfun(@(x)(Y = unique([Y x])),X,'UniformOutput',false)
ans = 
{
  [1,1] =

      1   17   20

  [2,1] =

      1    5   17   20   22   27

  [3,1] =

      1    2    5   17   18   20   21   22   27

}

Ok, but now Y is still empty:

octave:152> Y
Y = [](0x0)
octave:153> 

Clearly the Y name inside the anonymous function created and bound a new storage for its own version of Y.

What are the storage and name resolution rules in Octave/MATLAB? When is storage allocated for a variable? When are two identical names bound to the same variable? (Is there any way to effect the value of Y in the above anonymous function?)

Upvotes: 0

Views: 825

Answers (1)

Dusty Campbell
Dusty Campbell

Reputation: 3156

In Matlab functions have their own scope. When you pass a variable, unless that variable is also in the output list, it will not be modified by the called function; the function makes a copy of the variable and the copy is what the function modifies.

With anonymous functions the variable is copied at function declaration. See this Matlab documentation. This is what you are seeing with Y.

Also, I think that you are using cellfun incorrectly. You should not return the value of the anonymous function inside the call to cellfun, but as a result of cellfun.

So, perhaps this is closer to what you want:

octave:151> Y = cellfun(@(x, y)(unique([y x])),X,Y,'UniformOutput',false)

I can't tell if you want the result of each call to the anonymous function to change Y and use that result in the next call. If that is what you want, it will be more difficult.

Upvotes: 1

Related Questions