6

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.

Robert Seifert
  • 25,078
  • 11
  • 68
  • 113
oro777
  • 1,110
  • 1
  • 14
  • 29
  • 1
    The Matlab file exchange has a function called [`catstruct`](http://www.mathworks.com/matlabcentral/fileexchange/7842-catstruct) that seems to do the required task. Perhaps it will provide hints or even a complete solution. – mikkola Nov 19 '15 at 06:44
  • I don't think that using a for loop here is not good enough. Other possibilities are to use `struct2cell` if you have some sort of structure in your fieldnames and can generate them programmatically. – rst Nov 19 '15 at 06:46
  • what do you mean by 'not really a neat solution'? Why exactly isn't it a good solution? – Itamar Katz Nov 19 '15 at 07:07
  • Your question asks for the easiest but then says for loops are not "neat". For loops are easy. Do you want easy or neat? – Matt Nov 19 '15 at 07:23
  • Both if possible, I search the documentation for a function but I failed to find one. mikkoka> Thank you I will take a look to that file. RobertStettler> OK I think it is the Jojo's solution. – oro777 Nov 19 '15 at 07:25

2 Answers2

3

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.

Community
  • 1
  • 1
Robert Seifert
  • 25,078
  • 11
  • 68
  • 113
2

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

jolo
  • 423
  • 3
  • 10