matlabindexingmatlab-struct

Indexing/Accessing MATLAB nested structure


Hope, that I'm not creating a duplicate, but so far I didn't find the right answer for my problem.

Let's say, we have the following structure(s):

a(1).b = 1;
a(1).x.y = 2;

a(2).b = 3;
a(2).x.y = 4;

When I now try to get all values of b, I can do:

>> a(:).b

ans = 1
ans = 3

But how to this with the nested struct .x.y?

>> a(:).x.y

Expected one output from a curly brace or dot indexing expression, but there were 2 results.

Thanks for your help...!


Solution

  • Just loop over the indices.

    >> arrayfun(@(k) a(k).x.y, 1:numel(a))
    
    ans =
    
         2     4
    

    or:

    >> struct2array(cell2mat(extractfield(a,'x')))
    
    ans =
    
         2     4