How to find values in a nested struct with repeating fieldnames?
Show older comments
I've got a structure, of which I want to extract data. I think a loop in combination with the find function could do the trick, but this seems like an inefficient and error-prone way. Are there any better methods to obtain the same result?
The resulting structure is nested, where the same fieldnames typically repeat on every level. For example:
A = Struct with fields: X, Y, Z
where
Z = Struct with fields: X, Y, Z
My goal is to extract data from fieldname 'Y' when fieldname 'X' returns a specific value. However, this can be on any layer 'Z'. Hence, examples could be:
Solution = A.Z(ii).Y if A.Z(ii).X == searched value
or
Solution = A.Z(ii).Z(jj).Z(kk).Z(ll).Y if A.Z(ii).Z(jj).Z(kk).Z(ll).X == searched value
2 Comments
Stephen23
on 27 Nov 2024
Either loops or recursion, take your pick.
Oswin Hulsebos
on 29 Nov 2024
Accepted Answer
More Answers (1)
I think a loop in combination with the find function could do the trick, but this seems like an inefficient and error-prone way.
I don't know why you think the find() function would be used here. At most, you would need logical indexing.
As for loops, there is no efficient alternative to looping when dealing with structs and cells. Vectorization is only a thing that applies to numeric arrays,.
1 Comment
Oswin Hulsebos
on 29 Nov 2024
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!