Removing structure field if

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!

 Réponse acceptée

Walter Roberson
Walter Roberson le 26 Juin 2012

1 vote

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()

Plus de réponses (3)

the cyclist
the cyclist le 26 Juin 2012

1 vote

There might be a more efficient way to do this, but here is one way:
S1 = struct('name1',1,'name2',2);
S2 = struct('name1',1,'name3',3);
F1 = fieldnames(S1);
F2 = fieldnames(S2);
fieldsToRemove = setxor(F1,F2);
fieldsToRemoveFromS1 = intersect(F1,fieldsToRemove);
fieldsToRemoveFromS2 = intersect(F2,fieldsToRemove);
S1 = rmfield(S1,fieldsToRemoveFromS1)
S2 = rmfield(S2,fieldsToRemoveFromS2)

1 commentaire

the cyclist
the cyclist le 26 Juin 2012
Note that this method also removes fields from S1 that are not in S2, so you should get rid of that code if you didn't want that.

Connectez-vous pour commenter.

Jan
Jan le 26 Juin 2012

1 vote

Or:
fn1 = fieldnames(Struct1);
NewStruct = struct();
for K = 1 : length(fn1)
NewStruct.(fn1{K}) = Struct2.(fn1{K});
end
This has the advantage that the fieldnames of Struct1 and NewStruct have the same order, such that they can be joined to a struct array.

2 commentaires

Walter Roberson
Walter Roberson le 26 Juin 2012
Clear and simple.
The difference between your code and mine is that yours assumes that all fields in Struct1 will appear in Struct2 for sure.
Jan
Jan le 26 Juin 2012
@Walter: To be true, I've filleted your code, because I need some variables called "fn2" and "tf" as well as an intersect() for my own programs. :-)
I assume, my "keep it simple stupid" approach could match Anna's needs.

Connectez-vous pour commenter.

Anna
Anna le 28 Juin 2012

0 votes

Thanks so much for your inputs, problem solved :)

Catégories

Community Treasure Hunt

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

Start Hunting!

Translated by