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?

 채택된 답변

MathWorks Support Team
MathWorks Support Team 2023년 11월 15일
편집: MathWorks Support Team 2024년 1월 12일
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:

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Customize Object Indexing에 대해 자세히 알아보기

제품

릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by