필터 지우기
필터 지우기

Iterating Through Multiple Structures in One Structure

조회 수: 2 (최근 30일)
Spencer Ferris
Spencer Ferris 2021년 6월 13일
댓글: Walter Roberson 2021년 6월 13일
I have a 1x1 structure that has 12 fields in it, which are all structures of varying sizes that all have the exact same fields inside of them.
What I want to do is iterate through all 12 structures in a for loop and do the same things to each of them. How would I do this? Do the field names have a "index" value or something similar that I can use to iterate through them? I haven't been able to find an answer online.
I also have all 12 structures seperate from each other, so if I need to iterate through them seperately I could do that, it seemed like the best way to do it was to put them all into one structure.

채택된 답변

Walter Roberson
Walter Roberson 2021년 6월 13일
A = struct();
for K = 1 : 4
ts = struct('pqr', randi(9, 1, 3), 'stu', randi(9, 1, 3))
n = char(randi(0+['a', 'z'], 1, 5));
A.(n) = ts;
end
ts = struct with fields:
pqr: [5 9 8] stu: [6 1 4]
ts = struct with fields:
pqr: [3 9 7] stu: [8 8 8]
ts = struct with fields:
pqr: [5 5 6] stu: [6 7 2]
ts = struct with fields:
pqr: [7 3 4] stu: [5 7 7]
A
A = struct with fields:
zhanp: [1×1 struct] dqhtj: [1×1 struct] imnnu: [1×1 struct] bekzk: [1×1 struct]
structfun(@(S) [mean(S.pqr), sum(S.stu)], A, 'uniform', 0)
ans = struct with fields:
zhanp: [7.3333 11] dqhtj: [6.3333 24] imnnu: [5.3333 15] bekzk: [4.6667 19]
  댓글 수: 2
Spencer Ferris
Spencer Ferris 2021년 6월 13일
Thanks Walter! This looks like exactly what I want, quick follow-up question. I want to create plots of data in the structures. I created plots using your code and it looks like it did create the plots, but they are saved as 1 x 2 Line arrays, do you know how I'd go about getting those plots and exporting them as images?
Walter Roberson
Walter Roberson 2021년 6월 13일
If you are invoking plot() from within the structfun() then unless you are careful to create a new axes or figure each time, then the actual lines are likely to be deleted as soon as the next plot starts (unless you had "hold on").
I recommend making what you structfun() into a real function (not anonymous) that creates a figure and axes, plot()'s, creates appropriate annotations and legends, and print() or saveas() or exportgraphics().. and then deletes the figure.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Printing and Saving에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by