Concatenation structures: update structure fields without overwriting existing fields

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

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

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

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

Is there an easy way to do this. I manage to do this using the for loop and fieldnames() function to get the field name from S2 and put it in S1, but this is not a neat solution.

+6
source share
2 answers

This can help if you know that two structures do not have the same fields.

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

+2
source

I doubt that there is a real vectorized way. If you really need this small low speed, do not use structures.

Here is the loop solution:

 fn = fieldnames(S2) for ii = 1:numel(fn), S1.(fn{ii}) = S2.(fn{ii}); end 

The reason why there is no trivial solution is because Matlab cannot know in advance that there is no field c or d in S1 , and if so, then a conflict will arise.


Jolo's answer seems to be vectorized, although I don't know how these functions work internally. And they are probably not much faster than a simple loop.

+3
source

All Articles