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

11,028

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.

Share:
11,028
Chad
Author by

Chad

I am a Vehicle Powertrain Modeler at the National Renewable Energy Lab.

Updated on July 18, 2022

Comments

  • Chad
    Chad almost 2 years

    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
    Chad about 11 years
    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
    Chad about 11 years
    Unfortunately, the structs do not have all the same fields. The cellfun method worked beautifully! Thanks.