how to convert cell array of struct to matrix

3 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2020-8-18
编辑:Stephen23 2020-8-18
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).

请先登录,再进行评论。

回答(1 个)

Stephen23
Stephen23 2020-8-18
编辑:Stephen23 2020-8-18
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 个评论
Stephen23
Stephen23 2020-8-18
编辑:Stephen23 2020-8-18
"...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.
ORR
ORR 2020-8-18
yes.
dimentions of matrix being concatenated are not consistent

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

产品


版本

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by