Accessing field names in struct

4 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Structures 的更多信息

标签

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by