concatStruct
% Concatenates two structures into a new structure. They do not have to have the same fields.
This works for vector structures or structure arrays. Also works for nested structures.
Currently can only concatenate along 1 dimension across all fields if concatenating a vector structure.
% Example1 - vectors:
%
% Structure S1 has three fields, a, b, c. Structure S2 has 2 %fields, a and c. a and b are vectors, c is a cell array.
%
% S1.a = 1:10;
% S1.b = 2;
% S1.c = {'a', 'b', 'c'};
% S2.a = 11:20;
% S2.c = {'d', 'e', 'f'};
%
% S3 = concatStruct(S1,S2,'vec',2);
% S3 =
%
% a: [2x10 double]
% b: 2
% c: {2x3 cell}
%
%
% Example2 - structure arrays:
%
% S1(1).a = 1:10;
% S1(1).b = 1:10;
% S1(2).a = 2;
% S1(3).b = {'a', 'b', 'c'};
% S2(1).a = 11:20;
% S2(2).a = {'d', 'e', 'f'};
%
% S3 = concatStruct(S1,S2,'array',2);
% S3 =
%
% 1x5 struct array with fields:
% a
% b
%
%
% Example3 - structure arrays with mismatched dimensions:
%
% S1(1).a = 1:10;
% S1(1).b = 1:10;
% S1(2).a = 2;
% S1(3).b = {'a', 'b', 'c'};
%
% S1 =
%
% 1x3 struct array with fields:
% a
% b
%
% S2(1).a = 11:20;
% S2(2).a = {'d', 'e', 'f'};
% S2(2,1).a = 3;
%
% S2 =
%
% 2x2 struct array with fields:
% a
%
% S3 = concatStruct(S1,S2,'array',1);
% S3 =
%
% 3x3 struct array with fields:
% a
% b
%
% S4 = concat(S1,S2,'array',2);
% S4 =
%
% 2x5 struct array with fields:
% a
% b
Cite As
Gennady Erlikhman (2026). concatStruct (https://www.mathworks.com/matlabcentral/fileexchange/28193-concatstruct), MATLAB Central File Exchange. Retrieved .
MATLAB Release Compatibility
Platform Compatibility
Windows macOS LinuxCategories
Tags
Acknowledgements
Inspired by: unique_no_sort
Discover Live Editor
Create scripts with code, output, and formatted text in a single executable document.
| Version | Published | Release Notes | |
|---|---|---|---|
| 1.10.0.0 | Fixed some bugs.
|
||
| 1.9.0.0 | corrected description |
||
| 1.7.0.0 | Now works for m x n structures, not just vector structures. |
||
| 1.3.0.0 | No longer needs to take in vector structures. Can take in m x n structures. |
||
| 1.1.0.0 | added H1 line, error check for mismatching field dimensions, error check if field and substructure share same name, allows for concatenation of nested structures, added example |
||
| 1.0.0.0 |
