General indexing into structure
115 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi, i'm new to working with structures and couldn't seem to find the answer in the documentation. I'm trying to index into a structure to pull out values of one field that have a specific value in another. What I initially tried was structure(structure.field1 == 'string').field2. So what I want is all the values of field 2 that have a specific string in field 1. Any pointers would be appreciated. Also would like advice on how to explain this a bit better, as I realize this might be subpar.
0 commentaires
Réponse acceptée
Voss
le 12 Jan 2023
One way to do that is:
structure.field2(strcmp(structure.field1,'string'))
because you want to index into field2, not index into the structure itself, if I understand correctly.
There are other ways to do it, depending on whether the fields of the structure contain string arrays or cell arrays of character vectors.
Example 1, string arrays:
% fields contain string arrays
structure = struct('field1',["here" "are" "some" "strings"],'field2',["and" "some" "other" "strings"])
% the syntax suggested above works:
structure.field2(strcmp(structure.field1,'some'))
% so does this:
structure.field2(strcmp(structure.field1,"some"))
% so does this:
structure.field2(structure.field1 == "some")
% so does this:
structure.field2(structure.field1 == 'some') % similar to what you had
Example 2, cell arrays of character vectors:
% fields contain cell arrays of character vectors
structure = struct('field1',{{'here' 'are' 'some' 'character' 'vectors'}},'field2',{{'and' 'some' 'other' 'character' 'vectors'}})
% the syntax suggested above works:
structure.field2(strcmp(structure.field1,'some'))
% so does this:
structure.field2(strcmp(structure.field1,"some"))
% so does this:
structure.field2(structure.field1 == "some")
% but this gives an error:
structure.field2(structure.field1 == 'some') % similar to what you had
0 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Matrix Indexing 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!