10

Here's code that creates an example cell array for this question:

mycell = cell([5,1]);
for i = 1 : size(mycell)
    mystruct = struct();
    mycell{i} = mystruct;
    mycell{i}.field1 = i;
end

I expected mycell{:}.field1 to do what I want, but it gives an error. I can use the following for loop:

for i = 1 : size(mycell)
    mycell{i}.field1
end

but I'd prefer a simpler or more elegant solution as a want to use all the elements of mycell.field1 as the y-variables in a plot. Any ideas?

1 Answer 1

16

Two possible solutions:

First:

If all the structs in your cell array have the same fields than you can:

mycell = [ mycell{:} ]; % convert cell array to struct array
y = [ mycell(:).filed1 ]; % get the values

Second:

Another method uses cellfun

y = cellfun( @(x) x.field1, mycell );  

assuming all mycell{ii}.filed1 are scalars, otherwise you'll need to add 'UniformOutput', false to the cellfun.

note: in case some fields are empty ([]) these methods might not work as expected.

One small remark:
it is not a good practice to use i and j as variables in Matlab.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the note about i and j. I have definitely found debugging to be easier now that I'm not using them as for loop counters.
Unfortunately, the structs do not have all the same fields. The cellfun method worked beautifully! Thanks.

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.