2

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?

Adriaan
  • 17,741
  • 7
  • 42
  • 75
M.T Frieze
  • 23
  • 2

2 Answers2

3

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];
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • Thanks so much - your two-step solution works perfectly to extract a list from this cell array! – M.T Frieze Jan 28 '18 at 22:25
  • Glad I could help. And welcome to the site! You may want to mark the question as accepted (left tick mark in the upper left) if it does what you want – Luis Mendo Jan 28 '18 at 22:26
0

Using the answer above as a starting point, it is also possible to extract a 2d array of vectors from the Cell Array Structure. In each element of the 2d AllData cell array is a 2048 element vector called DataSet. The following commands will extract all of these vectors to a 2d array:

tmp = [AllData{:,1}];
len = length(tmp(1).DataSet); % Gets the length of one vector of DataSet
tmp2 = [tmp.DataSet];  % Extracts all vectors to a large 1-d array
AllDataSets = reshape(tmp2,len,[])';  % Reshapes into a 2d array of vectors
M.T Frieze
  • 23
  • 2