Clear Filters
Clear Filters

Accesing a field within a row of a data structure

1 view (last 30 days)
I have the following code
A=[DS.Carb]>2700;
B=[DS.Vit]==1;
C=or(A,B);
Index=find(C==1);
M=[DS.User_ID(Index)];
As you can see I am trying to acces some parts of the datastructure DS and save some information deending on "Index"
for exaple if Index=[3 4 67 8] then I would like to extract the content of the User_ID corresponding to the index each time

Accepted Answer

Voss
Voss on 6 May 2022
The correct syntax for getting the User_ID of elements at indices Index of struct array DS would be
M = [DS(Index).User_ID];
or
M = {DS(Index).User_ID};
depending on the class of the data stored in field User_ID.
For example:
DS = struct( ...
'User_ID',{1 2 3 4}, ...
'Carb',{2600 2800 2600 2800}, ...
'Vit',{0 0 1 1});
M = [DS([DS.Carb]>2700 | [DS.Vit]==1).User_ID]
M = 1×3
2 3 4
DS = struct( ...
'User_ID',{'one' 'two' 'three' 'four'}, ...
'Carb',{2600 2800 2600 2800}, ...
'Vit',{0 0 1 1});
M = {DS([DS.Carb]>2700 | [DS.Vit]==1).User_ID}
M = 1×3 cell array
{'two'} {'three'} {'four'}

More Answers (0)

Community Treasure Hunt

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

Start Hunting!