1
votes

In MATLAB, I have a struct array of the following form:

a(1).b.c = rand(1,10);
a(1).b.cSize = length(a(1).b.c);
a(2).b.c = rand(1,11);
a(2).b.cSize = length(a(2).b.c);
a(3).b.c = rand(1,12);
a(3).b.cSize = length(a(3).b.c);
a(4).b.c = rand(1,13);
a(4).b.cSize = length(a(4).b.c);
a(5).b.c = rand(1,14);
a(5).b.cSize = length(a(5).b.c);
a(6).b.c = rand(1,15);
a(6).b.cSize = length(a(6).b.c);

I would like to create a cell array c that contains the differently sized fields a.b.c of the nested struct, without using for loops.

I tried the following:

c = {a.b.c}

which is not working and returns the following error message:

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

The best solution I've found so far is the following

cellfun(@(x) x.c, {a.b}, 'UniformOutput', false)

Is there a faster solution without using cellfun? Maybe some reshape command?

2

2 Answers

1
votes

You can create a structrue array from a.b then extract the field c from the array.

ab = [a.b];
result = {ab.c}
1
votes

Just for fun, here's a one-line version of rahnema1's answer:

[result{1:numel(a)}] = subsref([a.b], substruct('.','c'));

I strongly discourage you from using this in the wild though, almost no-one understands this on first read (which is a good rule of thumb to use for coding).