Access data in a structure using a loop
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Isma_gp
am 7 Mär. 2017
Bearbeitet: Stephen23
am 7 Mär. 2017
Hi, I have a structure (str) with several files (file_1, file_2...). There is a variable (xt) I'd like to retrieve for each file, and save all the variables in 'a'.
For example, a{2,3} would contain the following information from the structure: a{2,3} = str.file_2.xt(3,:); I'd like to do this in a for loop to get a{ii,jj}, where ii=1:7 (file_ii) and jj=1:30 (xt(jj,:))
Can I get some help? Thanks
0 Kommentare
Akzeptierte Antwort
Stephen23
am 7 Mär. 2017
Bearbeitet: Stephen23
am 7 Mär. 2017
Best Solution: non-scalar structure
Your code would be a lot simpler if you used a non-scalar structure rather than dynamically accessing fieldnames like that. Then your task would be trivial to solve:
>> str(1).xt = [0,1;2,3;4,5];
>> str(2).xt = [6,7;8,9;10,11];
>> str(3).xt = [12,13;14,15;16,17]
>> out = num2cell(cat(3,str.xt),2);
>> out = permute(out,[3,1,2]);
and checking the output:
>> out{2,3}
ans =
10 11
Complicated Solution: dynamic fieldnames
If you insist on making your code more complicated than it needs to be, then you could try doing this:
str.file_1.xt = [0,1;2,3;4,5];
str.file_2.xt = [6,7;8,9;10,11];
str.file_3.xt = [12,13;14,15;16,17];
out = struct2cell(str);
out = [out{:}];
out = num2cell(cat(3,out.xt),2);
out = num2cell(out,2);
out = permute(out,[3,1,2]);
Note that the first two lines convert your nested structures into one non-scalar structure, thus making this answer just like the first one except more complicated. You would be better off storing your data in a non-scalar structure to start with (or perhaps an even simpler data variable, e.g. an ND numeric array).
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Structures finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!