Search code examples
matlabvectorizationmatlab-struct

Vectorized extracting a list from MATLAB Cell Array


I have a two-index MATLAB Cell Array (AllData{1:12,1:400}) where each element is a structure. I would like to extract a list of values from this structure.

For example, I would like to do something like this to obtain a list of 12 values from this structure

MaxList = AllData{1:12,1}.MaxVal;

This comes up with an error

Expected one output from a curly brace or dot indexing expression, but there were 12 results

I can do this as a loop, but would prefer to vectorize:

clear MaxList 
for i=1:12    
   MaxList(i) = AllData{i,1}.MaxVal; 
end

How do I vectorize this?


Solution

  • If all structs are scalar and have the same fields, it's better to avoid the cell array and directly use a struct array. For example,

    clear AllData
    AllData(1,1).MaxVal = 10;
    AllData(1,2).MaxVal = 11;
    AllData(2,1).MaxVal = 12;
    AllData(2,2).MaxVal = 13;
    [AllData(:).OtherField] = deal('abc');
    

    defines a 2×2 struct array. Then, what you want can be done simply as

    result = [AllData(:,1).MaxVal];
    

    If you really need a cell array of scalar structs, such as

    clear AllData
    AllData{1,1} = struct('MaxVal', 10, 'OtherField', 'abc');
    AllData{1,2} = struct('MaxVal', 11, 'OtherField', 'abc');
    AllData{2,1} = struct('MaxVal', 12, 'OtherField', 'abc');
    AllData{2,2} = struct('MaxVal', 13, 'OtherField', 'abc');
    

    you can use these two steps:

    tmp = [AllData{:,1}];
    result = [tmp.MaxVal];