how to convert cell array of struct to matrix

5 Ansichten (letzte 30 Tage)
ORR
ORR am 18 Aug. 2020
Bearbeitet: Stephen23 am 18 Aug. 2020
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 Kommentare
Stephen23
Stephen23 am 18 Aug. 2020
Bearbeitet: Stephen23 am 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).
ORR
ORR am 18 Aug. 2020
thanks

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Stephen23
Stephen23 am 18 Aug. 2020
Bearbeitet: Stephen23 am 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 Kommentare
Stephen23
Stephen23 am 18 Aug. 2020
Bearbeitet: Stephen23 am 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.
ORR
ORR am 18 Aug. 2020
yes.
dimentions of matrix being concatenated are not consistent

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Data Type Conversion finden Sie in Help Center und File Exchange

Produkte


Version

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by