Iterating Through Multiple Structures in One Structure

11 visualizaciones (últimos 30 días)
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.

Respuesta aceptada

Walter Roberson
Walter Roberson el 13 de Jun. de 2021
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 comentarios
Spencer Ferris
Spencer Ferris el 13 de Jun. de 2021
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 el 13 de Jun. de 2021
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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Printing and Saving en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by