Accessing field names in struct

4 visualizzazioni (ultimi 30 giorni)
Deepa Maheshvare
Deepa Maheshvare il 29 Gen 2020
Commentato: Stephen23 il 23 Dic 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?

Risposta accettata

Walter Roberson
Walter Roberson il 29 Gen 2020
F = fieldnames(test) ;
F(cell2mat(struct2cell(test)))

Più risposte (1)

Stephen23
Stephen23 il 23 Dic 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)}
R = 'g'
  1 Commento
Stephen23
Stephen23 il 23 Dic 2022
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

Accedi per commentare.

Categorie

Scopri di più su Structures in Help Center e File Exchange

Tag

Prodotti


Release

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by