How to copy field contents of one struct to another?

151 views (last 30 days)
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

Accepted Answer

Guillaume
Guillaume on 13 Jul 2015
Edited: Guillaume on 13 Jul 2015
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
  2 Comments
Chris
Chris on 26 Nov 2024 at 15:59
B.(fn{1})
returns the first value. If you have more than one value or data type (e.g., table) in the field, put this term in curly brackets { }:
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
Stephen23
Stephen23 on 26 Nov 2024 at 16:22
Edited: Stephen23 on 26 Nov 2024 at 16:23
"If you have more than one value or data type (e.g., table) in the field, put this term in curly brackets { }:"
How many values there are in one field is irrelevant. It actually depends on how many elements B has:
Depending on the data types and array sizes the functions HORZCAT, VERTCAT etc may also be useful.

Sign in to comment.

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!