General indexing into structure
59 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Blake Mitchell
el 12 de En. de 2023
Respondida: Voss
el 12 de En. de 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.
0 comentarios
Respuesta aceptada
Voss
el 12 de En. de 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 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Structures en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!