How to find values in a nested struct with repeating fieldnames?

7 ビュー (過去 30 日間)
Oswin Hulsebos
Oswin Hulsebos 2024 年 11 月 27 日
編集済み: Oswin Hulsebos 2024 年 11 月 29 日
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 件のコメント
Stephen23
Stephen23 2024 年 11 月 27 日
Either loops or recursion, take your pick.
Oswin Hulsebos
Oswin Hulsebos 2024 年 11 月 29 日
I was afraid so, thanks!

サインインしてコメントする。

採用された回答

Yash
Yash 2024 年 11 月 27 日
As @Stephen23 also suggested, recursion would be a good way to do this. Have a look at the example below:
% A is top layer and zVal is under A.Z
zVal = struct('X',2,'Y',4,'Z',struct([]));
A = struct('X',1,'Y',2,'Z',zVal);
% function call
getYIfXisVal(A,2)
ans = 4
% Function for recursion
function yVal = getYIfXisVal(st,val)
if(st.X==val)
yVal = st.Y;
else
yVal = getYIfXisVal(st.Z,val);
end
end
I hope this helps!
  1 件のコメント
Oswin Hulsebos
Oswin Hulsebos 2024 年 11 月 29 日
編集済み: Oswin Hulsebos 2024 年 11 月 29 日
This is indeed similar to what I had used so far, and can do the trick, thank you for your help!

サインインしてコメントする。

その他の回答 (1 件)

Matt J
Matt J 2024 年 11 月 27 日
編集済み: Matt J 2024 年 11 月 27 日
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 件のコメント
Oswin Hulsebos
Oswin Hulsebos 2024 年 11 月 29 日
I expected the find to be necessary when the searched value 'X' occurs multiple times, to return the correct indexing in the structure. However, with a recursion this does not seem to be necessary. Thank you for your comment!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by