General indexing into structure

115 vues (au cours des 30 derniers jours)
Blake Mitchell
Blake Mitchell le 12 Jan 2023
Réponse apportée : Voss le 12 Jan 2023
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.

Réponse acceptée

Voss
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"])
structure = struct with fields:
field1: ["here" "are" "some" "strings"] field2: ["and" "some" "other" "strings"]
% the syntax suggested above works:
structure.field2(strcmp(structure.field1,'some'))
ans = "other"
% so does this:
structure.field2(strcmp(structure.field1,"some"))
ans = "other"
% so does this:
structure.field2(structure.field1 == "some")
ans = "other"
% so does this:
structure.field2(structure.field1 == 'some') % similar to what you had
ans = "other"
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'}})
structure = struct with fields:
field1: {'here' 'are' 'some' 'character' 'vectors'} field2: {'and' 'some' 'other' 'character' 'vectors'}
% the syntax suggested above works:
structure.field2(strcmp(structure.field1,'some'))
ans = 1×1 cell array
{'other'}
% so does this:
structure.field2(strcmp(structure.field1,"some"))
ans = 1×1 cell array
{'other'}
% so does this:
structure.field2(structure.field1 == "some")
ans = 1×1 cell array
{'other'}
% but this gives an error:
structure.field2(structure.field1 == 'some') % similar to what you had
Operator '==' is not supported for operands of type 'cell'.

Plus de réponses (0)

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!

Translated by