MATLAB: Removing structure field if

isfieldremove fieldstructure

Hello,
I have two structures with a different number of fields. Struct1 has 75 fields and Struct2 has 111 fields. I would like to remove the fields from Struct2 that have a fieldname that is not equal to any of the field names in Struct1 so the two structures have the same number of fields with same field names. Alternatively I'd like to create a new structure that only has the fields from Struct2 that have field names equal to Struct1. I've tried for-if loops using 'isfield' and 'rmfield' and so on but I haven't managed to get anything to work yet. I'd really appreciate any help!

Best Answer

fn1 = fieldnames(Struct1);
fn2 = fieldnames(Struct2);
tf = ismember(fn2, fn1);
NewStruct = struct();
for K = 1 : length(tf)
if tf(K); NewStruct.(fn2{K}) = Struct2.(fn2{K}); end
end
I expect that is also a vectorized formulation that uses struct2cell()