MATLAB: Is it possible to concatenate two structures in MATLAB 7.5 (R2007b)

MATLAB

I have two MATLAB structures created using the STRUCT function. I would like to know if there is an equivalent of the CAT function that will let me concatenate them together.

Best Answer

If the structures have the same field names, you may contatenate them using [ ], HORZCAT or VERTCAT as follows:
S1 = struct('type', {'big1','little1'}, 'color', {'red1'}, 'x', {3 4})
S2 = struct('type', {'big2','little2'}, 'color', {'red2'}, 'x',{12,13})
% All of the following should work on these structs
[S1 S2]
[S1;S2]
horzcat(S1,S2)
cat(1,S1,S2)
cat(2,S1,S2)
The ability to concatenate two dissimilar structures (with different field names) is not available in MATLAB. For instance,
S1 = struct('type1', {'big1','little1'}, 'color1', {'red1'}, 'x1', {3 4})
S2 = struct('type2', {'big2','little2'}, 'color2', {'red2'}, 'x2',{12,13})
You may create a cell array of these structures,
S = {S1, S1}
Or, you may be able to do use the following approach to create a struct with a union of the field names. Any non-common fields will be set to [ ]
S = S1;
F = fieldnames(S2);
for i = length(S)+1:length(S)+length(S2)
for j = 1:length(F)
S(i).(F{j}) = S2.(F{j});
end
end