MATLAB: How to search a field in a structure and extract all fields that match

indexingstructure

Hopefully I'll explain clearly as I haven't worked with structures much. I have been given a large 1×1 structure of arrays with numerous fields. I want to search one field to match a specific string. I then want to extract from the structure all fields for those cases where the string matched. I would prefer to do this with out loops. For an array of structures, I've been able to use logical indexing to access and extract data using "index2 = cellfun(@(x) any(strcmp(x, test)), {diab2.preg})" and then just index into the structure, but this doesn't work for a structure of arrays.

Best Answer

Hi Dave,
I think, the following code snippet will help you.
s.f1= {'Sunday' 'Monday'}
s.f2= {'Sunday' 'Monday' 'Tuesday'}
s.f3= 'Tuesday'
s.f4= 'Wednesday'
s.f5= 'Thursday'
s.f6: 'Friday'
s.f7: 'Saturday'
index2 = structfun(@(x) any(strcmp(x, 'Monday')),s)
and the generated Output is
index2 =
7×1 logical array
1
1
0
0
0
0
0
Please refer this link for more details about 'structfun'.
Regards,
Sindhu