Search code examples
matlabsubsetcell-arraymatrix-indexing

Subsref with cells


This issue appeared when I was answering this question. It should be some stupid error I am doing, but I can't get what error it is…

myMatrix = [22 33; 44 55]

Returns:

>> subsref(myMatrix, struct('type','()','subs',{{[1 2]}} ) );    

ans =

    22    44

While using it with cells:

myCell = {2 3; 4 5} 

Returns:

>> subsref(myCell,struct('type','{}','subs',{{[1 2]}} ) );

ans =

     2  % WHATTT?? Shouldn't this be 2 and 4 Matlab??

Checking the subsref documentation, we see:

See how MATLAB calls subsref for the expression:

A{1:2} The syntax A{1:2} calls B = subsref(A,S) where S.type='{}' and S.subs={[1 2]}.

This seems not to be true because the returned value by subsref is just the first argument, not all arguments.

Then if one does:

>> [a,b]=subsref(myCell,struct('type','{}','subs',{{[1 2]}} ) ) 

a =

     2


b =

     4 % Surprise!

But this is not the same as myCell{[2 4]} which will automatically return:

>> myCell{[1 2]}                                               

ans =

     2


ans =

     4

I would need to use subsref with one output for every index I use access myCell, or am I missing something?


Solution

  • When the curly braces ({}) are used for indexing a cell array, the output is a comma-separated list. This implicitly calls subsref but the behavior is slightly different from invoking it directly.

    subsref by itself is a technically a function, and the comma-separated list returned by the curly braces simply behaves like varargout in this case. This means that you should specify an appropriate "sink" for all desired output results, just like you would do with any other function returning multiple parameters, otherwise they would be ignored.