Assignment between structures with common fields

Hi,
I have two structures A and B:
A = struct ('field1', {1,2}, 'field2', {3,4}, 'field3', {5,6});
B = struct ('field1', {7,8}, 'field2', {9,10});
Therefore A and B are:
A =
1x2 struct array with fields:
field1
field2
field3
B =
1x2 struct array with fields:
field1
field2
I want to assign the values of field1 and field2 from B to corresponding field1 and field2 of A. Structure arrays A and B have the same number of elements.
Is there any way for me to do this with the most efficiency?
Thanks

답변 (2개)

Sara
Sara 2014년 6월 27일

0 개 추천

If you do not want to assign all the fields of A to B, I'd do:
f = {'field1','field2'}; % list of fields
for i = 1:numel(f)
B.(f{i}) = A.(f{i});
end

댓글 수: 3

pietro
pietro 2014년 6월 28일
편집: pietro 2014년 6월 30일
Enhancing a bit Sara's example, you can get dynamically the list of common fields:
A=struct('p1',[],'p2',[]);
B=struct('p1',[],'p2',[],'p3',[]);
AF=fieldnames(A);
BF=fieldnames(B);
f=intersect(AF,BF);
and the you can go on with Sara's example.
Yeah, you'd think. You'd even think the simpler
A.field1 = B.field1
A.field2 = B.field2
would work, but none of them do. Just try it and see.
This is not quite what I was looking for, but a variant of this answer gives me a decent answer.
I want to assign values FROM B to A.
I can do the following:
A = struct ('field1', {1,2}, 'field2', {3,4}, 'field3', {5,6});
B = struct ('field1', {7,8}, 'field2', {9,10});
fields = fieldnames(B);
for ctr = 1:numel(fields)
[A.(fields{ctr})] = B.(fields{ctr});
end
Note the [] around the left hand side of the assignment. This was the only change from your answer (apart from assignment order).
Thanks for the help. I'd ideally want something more compact than this, maybe something without the need for a loop.

댓글을 달려면 로그인하십시오.

Image Analyst
Image Analyst 2014년 6월 28일

0 개 추천

Try it this way:
A = struct ('field1', {1,2}, 'field2', {3,4}, 'field3', {5,6})
B = struct ('field1', {7,8}, 'field2', {9,10})
numberOfStructuresA = length(A)
numberOfStructuresB = length(B)
if numberOfStructuresA ~= numberOfStructuresB
message = sprintf('You cannot assign all of the fields because the number of elements is different');
uiwait(warndlg(message));
return;
end
for k = 1 : numberOfStructuresA
A(k).field1 = B(k).field1
A(k).field2 = B(k).field2
end

카테고리

도움말 센터File Exchange에서 Structures에 대해 자세히 알아보기

태그

질문:

2014년 6월 27일

편집:

2014년 6월 30일

Community Treasure Hunt

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

Start Hunting!

Translated by