フィルターのクリア

Removing structure field if

7 ビュー (過去 30 日間)
Anna
Anna 2012 年 6 月 26 日
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 Center および File ExchangeStructures についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by