How can I access all field elements of a structure array nested in a cell array in MATLAB?

Chad picture Chad · Feb 14, 2013 · Viewed 10.8k times · Source

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?

Answer

Shai picture Shai · Feb 14, 2013

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.