General indexing into structure

103 views (last 30 days)
Blake Mitchell
Blake Mitchell on 12 Jan 2023
Answered: Voss on 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.

Accepted Answer

Voss
Voss on 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'.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!