General indexing into structure
조회 수: 103 (최근 30일)
이전 댓글 표시
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
채택된 답변
Voss
2023년 1월 12일
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!