How to loop over a structure in matlab
Mostrar comentarios más antiguos
Hi, I am new to matlab and learning it. I have a 1(1X1) main struct which again has 5(1X1) nested structs inside it which has 3(1X100) tables and I would like to finally fetch the value of those 3 tables but not sure how. Please help
3 comentarios
Walter Roberson
el 27 de Feb. de 2023
structfun()
MattC
el 27 de Feb. de 2023
@Learn Matlab: Please upload some representative data in a MAT file by clicking the paperclip button. It does not have to be your top-secret data, just something with exactly the same arrangement. Data descriptions are rarely correct.
Respuesta aceptada
Más respuestas (1)
Cameron
el 27 de Feb. de 2023
Depends on how your data is placed in the function. Like @Walter Roberson said, structfun works well if your data looks like this
T.S.X = rand(1,1000);
T.S.Y = rand(1,1000)*2;
T.S.Z = rand(1,1000)*3;
p = structfun(@median,T.S);
disp(p)
Another way to do it is to loop through them.
T.S.X{1} = rand(1,1000);
T.S.X{2} = rand(1,1000)*2;
T.S.X{3} = rand(1,1000)*3;
for xx = 1:length(T.S.X)
disp(median(T.S.X{xx}))
end
6 comentarios
MattC
el 27 de Feb. de 2023
Cameron
el 27 de Feb. de 2023
If you want something more specific you'll need to post your data (your variable Data) and what you'd like to do with it.
MattC
el 27 de Feb. de 2023
"Hope this information helps"
As far as I can tell, this means you would have 3x(number of fields in MainData) tables to store. How do you want to store them: in a cell array, or concatenating them together into three larger tables, or something else? Looping over structure fields is easy, but your question is not very clear because you have not specified what you want to do with those tables, e.g. how you want to store them.
Hopefully you are not planning on giving every table a unique variable name:
Walter Roberson
el 28 de Feb. de 2023
MainData --> Name1 --> Table 1(1x100), Table 2(1x100), Table 3(1x100)
Okay, that is 3 tables. Suppose you store those into variables named Table1, Table2 and Table3
MainData --> Name2 --> Table 1(1x100), Table 2(1x100), Table 3(1x100)
okay, that is 3 more tables. Do you want to now overwrite variables named Table1, Table2 and Table3 or do you want them stored into a different variable name?
If you were wanting to store to Table1{1} for Name1 and Table1{2} for Name2 and so on, using a cell array with one entry per field, then that is relatively easy. But if you want to store into (for example) Name1_Table1 and Name2_Table1 and so on, with the variable name depending on the field name, then the code gets uglier.
Categorías
Más información sobre Tables en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!