Accessing field names in struct

2 ビュー (過去 30 日間)
Deepa Maheshvare
Deepa Maheshvare 2020 年 1 月 29 日
コメント済み: Stephen23 2022 年 12 月 23 日
I've the following struct
test = struct(...
'a',false,...
'b',false,...
'c',false,...
'd',false,...
'e',false,...
'f',false,...
'g',true...
);
How do get the field name that has a value true ?
Expected result:
g
Any suggestions?

採用された回答

Walter Roberson
Walter Roberson 2020 年 1 月 29 日
F = fieldnames(test) ;
F(cell2mat(struct2cell(test)))

その他の回答 (1 件)

Stephen23
Stephen23 2022 年 12 月 23 日
test = struct(...
'a',false,...
'b',false,...
'c',false,...
'd',false,...
'e',false,...
'f',false,...
'g',true...
);
F = fieldnames(test);
R = F{structfun(@(a)a,test)}
R = 'g'
  1 件のコメント
Stephen23
Stephen23 2022 年 12 月 23 日
Timing tests:
test = struct(...
'a',false,...
'b',false,...
'c',false,...
'd',false,...
'e',false,...
'f',false,...
'g',true...
);
timeit(@()f1(test))
ans = 6.6802e-05
timeit(@()f2(test))
ans = 2.1892e-05
function f1(test)
F = fieldnames(test);
R = F(cell2mat(struct2cell(test)));
end
function f2(test)
F = fieldnames(test);
R = F{structfun(@(a)a,test)};
end

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

カテゴリ

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

タグ

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by