how to convert cell array of struct to matrix

Hey,
I have cell array, each contain struct.
data{1}.time=[1:10]
data{1}.pos=[1:10]
data{2}.time=[5:100]
data{2}.pos=[1:96]
i would like to create a time matrix and a pos matrix.
the matrix can be sparse or filled with nan where the size do not match tha max length of the time/pos vector.
so far i was using:
for n=1:2
time(1:length(data{n}.time),n)=data{n}.time
end
thanks

2 Comments

Stephen23
Stephen23 on 18 Aug 2020
Edited: Stephen23 on 18 Aug 2020
Note that square brackets are a concatenation operator, and are superfluous in this code: [1:10] because the colon operator already returns a vector, which you then concatenate with ... nothing. Get rid of the brackets, they literally do nothing**.
** except mislead experienced MATLAB users who know that they are a concatenation operator, and mislead beginners who believe that they are some kind of required "list" operator (which MATLAB does not have).

Sign in to comment.

Answers (1)

Stephen23
Stephen23 on 18 Aug 2020
Edited: Stephen23 on 18 Aug 2020
Rather than creating a cell array of scalar structures, you should create one single structure array:
>> S(1).time = 1:10; % I also removed the superfluous square brackets
>> S(1).pos = 1:10;
>> S(2).time = 5:100;
>> S(2).pos = 1:96;
Then you can trivially process all of the field data with one simple comma-separated list, e.g.:
>> Vtime = [S.time];
>> Vpos = [S.pos];
And you can use this to easily create the required matrix by downloading Jos's excellent padcat:
>> Mtime = padcat(S.time);
>> Mpos = padcat(S.pos);
Read more about comma-separated lists:
Note that you can also use a comma-separated list to convert your cell array of scalar structures to a much better structure array:
S = [data{:}];
(this requires that all of the structures have the same fields)

3 Comments

thanks but you created S as a 1X2 struct.
while my data is 1X2 cell. each cell contain the struct. this is how the data recieved.
Stephen23
Stephen23 on 18 Aug 2020
Edited: Stephen23 on 18 Aug 2020
"...while my data is 1X2 cell. each cell contain the struct."
Which is why at the end of my answer I showed how you can convert the cell array of structures to one structure array.
Did you try it?
Don't worry, that conversion will be quite efficient because it does not copy your data arrays, just creates a small list of references to them in memory.
yes.
dimentions of matrix being concatenated are not consistent

Sign in to comment.

Categories

Products

Release

R2017a

Asked:

ORR
on 18 Aug 2020

Edited:

on 18 Aug 2020

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!