how to convert cell array of struct to matrix
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Stephen23
il 18 Ago 2020
Modificato: Stephen23
il 18 Ago 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).
Risposte (1)
Stephen23
il 18 Ago 2020
Modificato: Stephen23
il 18 Ago 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];
>> 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 Commenti
Stephen23
il 18 Ago 2020
Modificato: Stephen23
il 18 Ago 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.
Vedere anche
Categorie
Scopri di più su Data Type Conversion in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!