필터 지우기
필터 지우기

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 CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by