Accessing all fields within a struct level at once

26 ビュー (過去 30 日間)
Vaishnavi
Vaishnavi 2023 年 12 月 19 日
編集済み: Nipun 2023 年 12 月 21 日
If I have a struct A which looks like:
A.('one').('include') ; A.('two').('include'); A.('three').('dont include');
and so on, how can I directly check if 'dont include' is present in the third level of the structure without having to use a loop. Is this possible to achieve without implementing a loop?
  2 件のコメント
Voss
Voss 2023 年 12 月 19 日
'dont include' is not a valid field name, so what does the struct really look like?
Rather than describing the struct, maybe it's better to save it in a .mat-file and upload it here (using the paperclip button).
Vaishnavi
Vaishnavi 2023 年 12 月 19 日
Hi, I've attached the mat file

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

採用された回答

Stephen23
Stephen23 2023 年 12 月 19 日
編集済み: Stephen23 2023 年 12 月 19 日
"Is this possible to achieve without implementing a loop?"
Not really, but you can hide the loop using STRUCTFUN:
A.one.include = 1;
A.two.include = 2;
A.three.dontinclude = 3;
F = @(s)isfield(s,'dontinclude');
structfun(F,A)
ans = 3×1 logical array
0 0 1
  2 件のコメント
Vaishnavi
Vaishnavi 2023 年 12 月 19 日
Hi, this is how my mat file looks like in reality
Stephen23
Stephen23 2023 年 12 月 19 日
"Hi, this is how my mat file looks like in reality"
Do you have another question?

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

その他の回答 (1 件)

Nipun
Nipun 2023 年 12 月 21 日
編集済み: Nipun 2023 年 12 月 21 日
Hi Vaishnavi,
I understand that you are trying to find if "dontinclude" is a structure property without using for loops.
One possible solution is to create a function which evaluates every level of structure to check if the property is present.
Here is an example code with the listed recommendation
funcCheck = @(struct)isfield(struct,'dontinclude');
structfun(funcCheck,A)
Returns a "n x 1" logical array, where "n" is the number of levels in the structure.
Link to documentation:
  1. STRUCTFUN : Apply function to each field of scalar structure - MATLAB structfun - MathWorks India
Hope this helps.
Regards,
Nipun

カテゴリ

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