MATLAB Answers

Why is subsref and subscripted reference not equivalent

1 view (last 30 days)
Reza Housseini
Reza Housseini on 21 Feb 2017
Answered: Kenneth Eaton on 21 Feb 2017
Assume an struct array with the following content:
A = struct('b', {1, 2});
Following two code blocks do not give the same output:
[A.b]
ans =
1 2
and
S = struct('type', {'.'}, 'subs', {'b'});
[subsref(A, S)]
ans =
1
But I would say this two referencing methods are equal. What is the workaround for using subsref?

  3 Comments

Alexandra Harkai
Alexandra Harkai on 21 Feb 2017
Not sure if it helps, but it makes a difference whether the underlying data is a cell array or not:
B = struct('b', [1, 2]);
[B.b]
ans =
1 2
and
S = struct('type', {'.'}, 'subs', {'b'});
[subsref(B, S)]
ans =
1 2
If it's not a cell array, the two referencing methods seem to be equivalent.
Jan
Jan on 21 Feb 2017
@Alexandra: B = struct('b', [1, 2]) creates a scalar struct, while the detail matters, that A = struct('b', {1, 2}) is a struct array.

Sign in to comment.

Answers (2)

Kenneth Eaton
Kenneth Eaton on 21 Feb 2017
Not sure if this is a complete answer, but it appears that invoking subsref directly requires a stricter definition of the output arguments. While:
A.b
will automatically dump all possible output arguments in a comma separated list, calling subsref directly requires you to explicitly define how many output arguments you want. The only way I've figured out thus far to get them all is to collect them in a cell array of the appropriate size:
>> [out{1:numel(A)}]=subsref(A, S)
out =
1×2 cell array
[1] [2]
>> [out{:}]
ans =
1 2

  0 Comments

Sign in to comment.


Jan
Jan on 21 Feb 2017
Edited: Jan on 21 Feb 2017
Not an answer: I've played around with
S = struct('type', {'()', '.'}, 'subs', {{':'}, 'b'});
[subsref(A, S)]
because
[A.b]
is actually:
[A(:).b]
But this still replies 1 instead of the expected [1,2]. Then my interest in the question growed and I've voted for it. I expect, that there is a simple solution, by I cannot find it currently.

  0 Comments

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by