Structs fields indexing issue

3 ビュー (過去 30 日間)
Lask
Lask 2018 年 3 月 7 日
コメント済み: Jos (10584) 2018 年 3 月 7 日
Hi,
I have a structure 'Parent', which stores three structs named 'Child1','Child2' and 'Child3' (these structs have the same fields with different values). I would like to know how to find if any of those 3 structs matches a condition. For example, something like:
find(Parent.*.field_1 == 2)
any help would be appreciated.

採用された回答

Stephen23
Stephen23 2018 年 3 月 7 日
編集済み: Stephen23 2018 年 3 月 7 日
If all of the child structures have exactly the same fields then you would be much better off using a non-scalar structure instead of nested structures:
S(1).field = ...
S(2).field = ...
S(3).field = ...
Then you could trivially do this:
find([S.field] == 2)
Using a non-scalar structure would make your code much simpler and more efficient.
  1 件のコメント
Jos (10584)
Jos (10584) 2018 年 3 月 7 日
While Stephen is absolutely right about the benefits of using an array of structures, take note that this concatenation would yield different indices from applying find on each structure element separately:
A(1).f = [1 2] ;
A(2).f = [2 3 2] ;
find([A.f]==2) % → 2 3 5 !
[find(A(1).f==2) find(A(2).f==2)] % → 2 1 3 !

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

その他の回答 (1 件)

Jos (10584)
Jos (10584) 2018 年 3 月 7 日
Parent.Child1.field_1 = [1 2 2 3] ;
Parent.Child2.field_1 = [1 3 3 2 3 2] ;
Parent.Child3.field_1 = [2] ;
A = structfun(@(S) find(S.field_1==2), Parent, 'un', 0)
A = horzcat(A{:})

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by