How to loop over a structure in matlab
이전 댓글 표시
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
Walter Roberson
2023년 2월 27일
structfun()
MattC
2023년 2월 27일
@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.
채택된 답변
추가 답변 (1개)
Cameron
2023년 2월 27일
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
MattC
2023년 2월 27일
Cameron
2023년 2월 27일
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
2023년 2월 27일
"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
2023년 2월 28일
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.
카테고리
도움말 센터 및 File Exchange에서 Tables에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!