Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 360
oro777 Avatar asked Nov 19 '15 06:11

oro777


2 Answers

I doubt there is real vectorized way. If you really need that last little tiny bit of speed, don't use structs.

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 that Matlab can't know in advance that there is no field c or d in S1, and if so, there would be a conflict.


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

like image 186
Robert Seifert Avatar answered Nov 09 '22 04:11

Robert Seifert


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{:});

like image 21
jolo Avatar answered Nov 09 '22 03:11

jolo