# How to extract data from a cell array which contains structs?

83 views (last 30 days)
Alon Rozen on 15 Aug 2017
Commented: Alon Rozen on 15 Aug 2017
Hi all,
I have the following problem: I have a cell array which contains in each cell a certain struct (structs have the same fields but different information). Suppose a certain field contain numbers. I want to create an array from all the numbers of this field from all the structs in the cell array. I can do this with a for loop but I guess there should be a better and a faster way. I tried to do it using 'deal' but failed.
Is there a better way?
Thanks, Alon

Stephen Cobeldick on 15 Aug 2017
Edited: Stephen Cobeldick on 15 Aug 2017
Something like this might work for you:
cell2mat(cellfun(@(s)s.field,C,'uni',0))
it assumes that the data is able to be concatenated into one array, and that the structures are scalar. You will need to use the correct fieldname, and orient the input cell array and its contents to suit your data (you did not give any info about this). Here is an example:
>> C{1,1} = struct('A',1:3);
>> C{2,1} = struct('A',4:6);
>> C{3,1} = struct('A',7:9);
>> cell2mat(cellfun(@(s)s.A,C,'uni',0))
ans =
1 2 3
4 5 6
7 8 9
"Is there a better way?"
This task would be much simpler if you simply used one non-scalar structure, then you could simply do this:
cat(1,S.field)
[S.field]
vertcat(S.field)
etc.
For example:
>> S(1).A = 1:3;
>> S(2).A = 4:6;
>> S(3).A = 7:9;
>> vertcat(S.A)
ans =
1 2 3
4 5 6
7 8 9
Do you see how much simpler the code is, because I stored the data in a much better way?

Alon Rozen on 15 Aug 2017
Thanks Stephen,
I am not sure I got it right - tried few examples. Suppose the struct is not only scalars and looks like this: My_Struct.Name
My_Struct.Age
My_Struct.Some_Matrix (lets say 3x3 matrix)
Suppose 'S' is a 4x1 cell array where each cell contains a different instance of the sruct 'My_Struct'.
How can I get, for example, an array with values of the field 'Age'?
Guillaume on 15 Aug 2017
In your example there's no reason for the cell array. You could just have a 4x1 struct:
S = vertcat(S{:});
it is then trivial to get the age matrix:
vertcat(S.Age)
If you insist on keeping the cell array, then as Stephen showed:
cell2mat(cellfun(@(s) s.Age, S, 'UniformOutput', false))
A lot more obscure and slower!
Alon Rozen on 15 Aug 2017
Thanks Stephen and Guillaume :)
Now I understand it and it works.
As for not using a cell - I know it would be easier. I gave just a simple example to make things clear. My real cell array cannot be represented by a struct - it is a bit complicated.