Changing a matrix of nested structures to an array of cells with elements of different sizes

In MATLAB, I have an array of structures 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 different sized fields of a a.b.c

nested structure without using for loops.

I tried the following:

c = {a.b.c}

      

which doesn't work and returns the following error message:

Expected one result from curly brace or point indexing, but there were 6 results.

The best solution I have found so far is the following

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

      

Is there a faster, no-use solution cellfun

? Maybe a team reshape

?

+1


source to share


2 answers


You can create an array structrue from a.b

, then extract a field from the array c

.



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

      

+1


source


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, although almost no one gets it on first reading (which is a good rule of thumb to use for coding).

+1


source







All Articles