Removing structure field if

7 views (last 30 days)
Anna
Anna on 26 Jun 2012
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!

Accepted Answer

Walter Roberson
Walter Roberson on 26 Jun 2012
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()

More Answers (3)

the cyclist
the cyclist on 26 Jun 2012
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 Comment
the cyclist
the cyclist on 26 Jun 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.

Sign in to comment.


Jan
Jan on 26 Jun 2012
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 Comments
Walter Roberson
Walter Roberson on 26 Jun 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 on 26 Jun 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.

Sign in to comment.


Anna
Anna on 28 Jun 2012
Thanks so much for your inputs, problem solved :)

Categories

Find more on Structures in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!