MATLAB: Filter a struct based on the field name.

MATLABstructstructures

Hi all. Assume that i have a struct like the following
my_struct:
f1_x : 0
f1_y : 1
f1_z : 3
f2_x : -1
f2_y : 2
f3_y : 0
My question is how to filter based on the field name (of better, based on part of the field name). For example, if I want to filter all the fields that start with the string f1_, thus obtaning
my_struct_f1:
f1_x : 0
f1_y : 1
f1_z : 3
what should I do? Many thanks in advance.

Best Answer

names = fieldnames( myStruct );
subStr = 'f1_';
filteredStruct = rmfield( myStruct, names( find( cellfun( @isempty, strfind( names , subStr ) ) ) ) );
should work, based on a quick test, though there may be more efficient methods.