Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update struct via another struct in Matlab [duplicate]

Tags:

struct

matlab

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.

like image 730
M1L0U Avatar asked Mar 06 '13 10:03

M1L0U


1 Answers

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).

like image 61
Eitan T Avatar answered Oct 17 '22 15:10

Eitan T