Removing structure field if

7 次查看(过去 30 天)
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!

采纳的回答

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

更多回答(3 个)

the cyclist
the cyclist 2012-6-26
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 个评论
the cyclist
the cyclist 2012-6-26
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.

请先登录,再进行评论。


Jan
Jan 2012-6-26
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 个评论
Walter Roberson
Walter Roberson 2012-6-26
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 2012-6-26
@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.

请先登录,再进行评论。


Anna
Anna 2012-6-28
Thanks so much for your inputs, problem solved :)

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by