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?

Chad
  • 1,434
  • 1
  • 15
  • 30

1 Answers1

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.

Community
  • 1
  • 1
Shai
  • 111,146
  • 38
  • 238
  • 371
  • 1
    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. – Chad Feb 14 '13 at 21:15
  • 1
    Unfortunately, the structs do not have all the same fields. The cellfun method worked beautifully! Thanks. – Chad Feb 14 '13 at 21:45