Assignment between structures with common fields
1 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(2 个)
Sara
2014-6-27
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 个评论
Image Analyst
2014-6-28
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.
Image Analyst
2014-6-28
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!