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일

0 개 추천

F = fieldnames(test) ;
F(cell2mat(struct2cell(test)))

추가 답변 (1개)

Stephen23
Stephen23 2022년 12월 23일

1 개 추천

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

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

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Structures에 대해 자세히 알아보기

제품

릴리스

R2019b

태그

질문:

2020년 1월 29일

댓글:

2022년 12월 23일

Community Treasure Hunt

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

Start Hunting!

Translated by