matlabstructfield-names

Concatenate structs: Update struct fields without overwriting existing fields


I would like to know the easiest way to update a Matlab structure from another structure with different fields. Please see my example to understand what I mean. I have two structures S1 and S2 with different fieldnames which I want to combine.

S1.a = 1;
S1.b = 2;
S2.c = 3;
S2.d = 4;

If I write S1 = S2; the S1 structure will obviously be overwritten by S2. I want the result to be as the following code :

S1.a = 1;
S1.b = 2;
S1.c = 3;
S1.d = 4;

Is there an easy way to do so. I manage to do it by using a for loop and the fieldnames() function in order to get the fieldname from S2 and put it in S1 but it is not really a neat solution.


Solution

  • This might help if you know the two structs don't have the same fields

    tmp = [fieldnames(S1), struct2cell(S1); fieldnames(S2), struct2cell(S2)].'; S1 = struct(tmp{:});