8

I'm wondering if there is a convenient way to update a struct with the values of another struct in Matlab. Here is the code, with the use of fieldnames, numel and a for loop,

fn = fieldnames(new_values);
for fi=1:numel(fn)
    old_struct.(fn{fi}) = new_values.(fn{fi});
end

Of course, I don't want to loose the fields in old_struct that are not in new_values, so I can't use the simple old_struct=new_values.

Updating a struct is something we may want to do in a single short line in an interpreter.

Shai
  • 111,146
  • 38
  • 238
  • 371
M1L0U
  • 1,175
  • 12
  • 20
  • 4
    http://blogs.mathworks.com/loren/2009/10/15/concatenating-structs/ – Dan Mar 06 '13 at 11:29
  • Theses answers are either not relevant (assuming no collision) or use the same `for` loop + `fieldnames` method. This tends to confirm the fact that there is no simpler way, but does not give a clean evidence ;) – M1L0U Mar 06 '13 at 14:41

1 Answers1

6

Since you are convinced that there is no simpler way to achieve what you want, here is the method described in Loren Shure's article (see link posted in Dan's comment), applied to your example:

%// Remove overlapping fields from first struct
s_merged = rmfield(s_old, intersect(fieldnames(s_old), fieldnames(s_new)));

%// Obtain all unique names of remaining fields
names = [fieldnames(s_merged); fieldnames(s_new)];

%// Merge both structs
s_merged = cell2struct([struct2cell(s_merged); struct2cell(s_new)], names, 1);

Note that this slightly improved version can handle arrays of structs, as well as structs with overlapping field names (this is what I believe you call collision).

Eitan T
  • 32,660
  • 14
  • 72
  • 109