Return field in struct whose field name contains a string

조회 수: 102 (최근 30일)
Cody Brown
Cody Brown 2021년 4월 13일
답변: Cris LaPierre 2021년 4월 13일
i have a struct like the following:
Struct.Data.FieldOne %1000x2 double
Struct.Data.FieldTwo %1000x2 double
Struct.Data.FieldThree %1000x2 double
I want to return the field that contains a string, like the following:
Two = find(Struct.Data, 'Two'); %I don't know what this function would be
that is equevelent to:
Two = Struct.Data.FieldTwo;

답변 (1개)

Cris LaPierre
Cris LaPierre 2021년 4월 13일
One way is to use the functions fieldnames and contains.
Struct.Data.FieldOne =1;%1000x2 double
Struct.Data.FieldTwo =2;%1000x2 double
Struct.Data.FieldThree =3;%1000x2 double
% get field names
nm = fieldnames(Struct.Data)
nm = 3×1 cell array
{'FieldOne' } {'FieldTwo' } {'FieldThree'}
% find which field contains the search string
ind = contains(nm,'Two')
ind = 3×1 logical array
0 1 0
% Dynamically extract the data
two = Struct.Data.(nm{ind})
two = 2
Note that this approach will only work when there is a single match.

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by