필터 지우기
필터 지우기

How to copy field contents of one struct to another?

조회 수: 149 (최근 30일)
Ralf
Ralf 2015년 7월 13일
편집: Guillaume 2015년 7월 13일
Hi all,
I have got two structs, A and B. B has a subset of the fields of A:
A.f1 = 1;
A.f2 = 2;
A.f3 = 3;
B.f1 = 4;
B.f2 = 5;
Now I want to copy all field content of B to the corresponding fields of struct A, leaving the other fields of A unchanged:
A.f1 = B.f1;
A.f2 = B.f2;
% A.f3 == 3 untouched
Is there a simply way to achieve this for arbitraty structs A and B, considering that B's field names are always a subset of A's field names?
Thank you very much, Ralf

채택된 답변

Guillaume
Guillaume 2015년 7월 13일
편집: Guillaume 2015년 7월 13일
Iterate over the fieldnames of B to copy them using dynamic field names:
A = struct('f1', 1, 'f2', 2, 'f3', 3);
B = struct('f1', 4, 'f2', 5);
for fn = fieldnames(B)'
A.(fn{1}) = B.(fn{1});
end

추가 답변 (0개)

카테고리

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