1

Quick question that took me a little fiddling to solve neatly...

Take two structs with unique fields.

% Struct #1
S_1.a = 1;
S_1.b = 2;
S_1.c = 3;

% Struct #2
S_2.d = 1;
S_2.e = 2;

How to merge them into a single struct that contains all of both structs?

MATLAB does not, AFAIK, have a command to automate combining structures.

The obvious method of manually typing: S_1.d = S_2.d; is, of course, frustrating and an inefficient use of your time.

Mark_Anderson
  • 1,229
  • 1
  • 12
  • 34
  • The suggested duplicate doesn't turn up in search for "MATLAB combine struct" or similar. The duplicate can only be found by entering "structure" in the search term, so it's not very useful for someone looking up combining structs in matlab (as I did, before wrangling a solution together). I'd suggest either editing the other post to hopefully give it search relevance, or leaving both up with the duplicate marker to expose readers to both questions. – Mark_Anderson Mar 19 '18 at 21:59
  • FWIW, it's the first Google result for `matlab combine structure site:stackoverflow.com`. But yes, that is the point of marking questions as duplicates. – sco1 Mar 19 '18 at 22:05

1 Answers1

2

One solution is to loop over fieldnames

% Combine  into a single output structure
f = fieldnames(S_2);
for i = 1:size(f,1)
    S_1.(f{i}) = S_2.(f{i});
end

A weakness of this method is that fields with the same name are overwritten without warning. This can be flagged via strcmp. A slower but more robust function would therefore be:

function S_out = combineStructs(S_1,S_2)
%  Combines structures "S_1","S_2" into single struct "S_out"
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Get fieldnames
f_1 = fieldnames(S_1);
f_2 = fieldnames(S_2);

%Check for clashes
for i = 1:size(f_1,1)
    f_i = f_1{i};
    if max(strcmp(f_i,f_2)) %strcmp returns logic array.
        %Pop-up msg; programme continues after clicking
        errordlg({'The following field is repeated in both structs:';'';...
            f_i;'';...
            'To avoid unintentional overwrite of this field, the program will now exit with error'},...
            'Inputs Invalid!')
        %Exit message; forces quit from programme gives a pop-up
        error('Exit due to repeated field in structure')
    end
end

% Combine  into a single output structure
for i = 1:size(f_1,1)
    S_out.(f_1{i}) = S_1.(f_1{i});
end
for i = 1:size(f_2,1)
    S_out.(f_2{i}) = S_2.(f_2{i});
end

end
Mark_Anderson
  • 1,229
  • 1
  • 12
  • 34