Return field in struct whose field name contains a string
74 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
i have a struct like the following:
Struct.Data.FieldOne %1000x2 double
Struct.Data.FieldTwo %1000x2 double
Struct.Data.FieldThree %1000x2 double
I want to return the field that contains a string, like the following:
Two = find(Struct.Data, 'Two'); %I don't know what this function would be
that is equevelent to:
Two = Struct.Data.FieldTwo;
0 commentaires
Réponses (1)
Cris LaPierre
le 13 Avr 2021
One way is to use the functions fieldnames and contains.
Struct.Data.FieldOne =1;%1000x2 double
Struct.Data.FieldTwo =2;%1000x2 double
Struct.Data.FieldThree =3;%1000x2 double
% get field names
nm = fieldnames(Struct.Data)
% find which field contains the search string
ind = contains(nm,'Two')
% Dynamically extract the data
two = Struct.Data.(nm{ind})
Note that this approach will only work when there is a single match.
0 commentaires
Voir également
Catégories
En savoir plus sur Structures dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!