Search code examples
matlaboctave

Why filtering some rows in a cellarray has a different behaviour on an assignment in Octave?


I am trying to return in Octave a filtered cellarray with strings and I am getting a behaviour that I do not understand.

Filtering a couple of row index seems to work, but when that is assigned to a variable and returned by a function it does not work.

I do not know if this behaviour takes place in Matlab too.

Why is this happening?

    function result = testcellarray()                                                                             
                                                                                                                   
      mycell = {'foo1' 'foo2' 'foo3'; 'barbar1' 'barbar2' 'barbar3'; 'yuzz1' 'yuzz2' 'yuzz3'};              
      idx = [1; 3];                                                                                         
    
      % WANT TO RETURN THIS                                                                                 
      mycell{[1:3], 2}                                                                                      
    
      % BUT RESULT GETS SOMETHING DIFFERENT                                                                
      result = mycell{[1:3], 2}                                                                             
    
    end
    
    octave:221> testcellarray()
          ans = foo2
          ans = barbar2
          ans = yuzz2
          result = foo2
          ans = foo2


Solution

  • mycell{[1:3], 2} returns a comma-separated list of three values. You can tell because Octave shows three times ans = before the function returns.

    The assignment then is basically equal to

    result = 'foo2', 'barbar2', 'yuzz2'
    

    Commas can separate statements in the MATLAB language, so this line has three statements, only the first one is an assignment.

    If you want to return a subset of a cell array, use parenthesis (round brackets) for indexing:

    result = mycell([1:3], 2)
    

    You can also capture the comma-separated list inside curly brackets to form a new cell array with the three values. This will then be a 1x3 cell array, instead of the 3x1 array we returned above:

    result = {mycell{[1:3], 2}}