Convert data in nested structure to array

8 views (last 30 days)
Luca Amerio
Luca Amerio on 4 Feb 2015
Answered: Tim Baur on 31 Mar 2022
Hi everybody,
I have a nested structure like this one:
S.a1.b1.x=1
S.a1.b1.y=2
S.a1.b1.u=3
S.a1.b1.v=4
S.a1.b2.x=5
S.a1.b2.y=6
S.a1.b2.u=7
S.a1.b2.v=8
S.a2.b1.x=9
S.a2.b1.y=10
S.a2.b1.u=11
S.a2.b1.v=12
S.a2.b2.x=13
S.a2.b2.y=14
S.a2.b2.u=15
S.a2.b2.v=16
Now I would like to plot all the data in the structure using quiver. To do so I need to extract all the x, y, u and v in the structure with something like:
X=S.(:).(:).x
Y=S.(:).(:).y
U=S.(:).(:).u
V=S.(:).(:).v
quiver(X,Y,U,V)
Which is the best (readable, fast, best-practice) way to do so? I'm starting to think that maybe it has been wrong to save these data into a nested struct. Is there a better way?
In order to answer this latter question I need to point out that the user must be able to specify which "a" (a1, a2, ...) sub structure to extract. That's the reason why I decided to use a structure in first instance: to be able to use commands like
S.(choice).b1
S.(choice).b2
ecc
Thank you very much,
Luca Amerio

Answers (2)

Guillaume
Guillaume on 4 Feb 2015
The most straightforward I can think of getting at your data is using structfun repeatedly on each subfield
points = cell2mat(structfun(@(fa) {cell2mat(structfun(@(fb) {structfun(@(fxyzu) fxyzu, fb)'}, fa))}, S);
XYUV = num2cell(points, 1);
quiver(XYUV{:})

Tim Baur
Tim Baur on 31 Mar 2022
Would you know a solution that could extract the desired values/rangens dynamically from a structured array, too?
So depending on the number of levels and the selected indeces, e.g.:
X = S(1:3).a(:).b(1).c(4:5).d >> 4x nested structfun
X = S(1:3).a(:) >> 1x nested structfun
X = S(1:3).a(:).b(1).c(4:5).d.e.f.g.h(:) >> 8x nested structfun
etc.
That would be super useful in case the depth of the structure is not always the same

Categories

Find more on Structures in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!