1

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 Answers 2

1

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

ab = [a.b];
result = {ab.c}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your solution. Could you please have a look at my new question with a different form of the nested structure.
1

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.