How to get multiple outputs from SUBSREF call when accessing cell array?

Consider the following example, where I access all contents of a cell array directly, e.g. 
>> c = {'A','B'}
c =
  1×2 cell array
    {'A'}    {'B'}
>> c{:}
ans =
    'A'
ans =
    'B'
This returns both elements, whereas an access via subsref and trying to capture both results in a cell returns the first element only, e.g.
>> subStr = substruct('{}',{':'});
>> subsref(c,subStr)
ans =
    'A'
How can I get multiple outputs from subsref call when accessing a cell array?

 Accepted Answer

This is expected behavior and the way the MATLAB language works. Note that subsref is a function call: a call to any function with no explicit output arguments implicitly asks for at most one output. If you want two outputs you must ask for them explicitly.
Please run the following command in MATLAB R2018a to refer to the workaround in our documentation:
web(fullfile(docroot, 'matlab/ref/numargumentsfromsubscript.html'))
First, you use the numArgumentsFromSubscript function to get the number of expected outputs from subsref like this:
>> n = numArgumentsFromSubscript(c,subStr,matlab.mixin.util.IndexingContext.Statement)
n =
     2
Then, you are creating an empty 1-by-n cell array and assign all available outputs to it by writing:
>> d = cell(1,n);
>> [d{:}] = subsref(c,subStr)
d =
  1×2 cell array
    {'A'}    {'B'}
Please follow the below link to search for the required information regarding the current release:

More Answers (0)

Categories

Products

Release

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!