Accessing field names in struct
7 views (last 30 days)
Show older comments
Deepa Maheshvare
on 29 Jan 2020
Commented: Stephen23
on 23 Dec 2022
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?
0 Comments
Accepted Answer
More Answers (1)
Stephen23
on 23 Dec 2022
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)}
1 Comment
Stephen23
on 23 Dec 2022
Timing tests:
test = struct(...
'a',false,...
'b',false,...
'c',false,...
'd',false,...
'e',false,...
'f',false,...
'g',true...
);
timeit(@()f1(test))
timeit(@()f2(test))
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
See Also
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!