Concatenate Structures
This example shows how to concatenate structure arrays using the [] operator. To concatenate
structures, they must have the same set of fields, but the fields do not need to contain the same sizes
or types of data.
Create scalar (1-by-1) structure arrays struct1 and struct2, each with fields a and b:
struct1.a = 'first';
struct1.b = [1,2,3];
struct2.a = 'second';
struct2.b = rand(5);
struct1,struct2
struct1 = struct with fields:
a: 'first'
b: [1 2 3]
struct2 = struct with fields:
a: 'second'
b: [5x5 double]
Just as concatenating two scalar values such as [1,2] creates a 1-by-2 numeric array, concatenating
struct1 and struct2 creates a 1-by-2 structure array.
combined = [struct1,struct2]
combined=1×2 struct array with fields:
a
b
When you want to access the contents of a particular field, specify the index of the structure in the
array. For example, access field a of the first structure.
combined(1).a
ans =
'first'
Concatenation also applies to nonscalar structure arrays. For example, create a 2-by-2 structure
array named new. Because the 1-by-2 structure combined and the 2-by-2 structure new both have
two columns, you can concatenate them vertically with a semicolon separator.
new(1,1).a = 1;
new(1,1).b = 10;
new(1,2).a = 2;
new(1,2).b = 20;
new(2,1).a = 3;
new(2,1).b = 30;
new(2,2).a = 4;
new(2,2).b = 40;
larger = [combined; new]
larger=3×2 struct array with fields:
a
11 Structures
11-8
This example shows how to concatenate structure arrays using the [] operator. To concatenate
structures, they must have the same set of fields, but the fields do not need to contain the same sizes
or types of data.
Create scalar (1-by-1) structure arrays struct1 and struct2, each with fields a and b:
struct1.a = 'first';
struct1.b = [1,2,3];
struct2.a = 'second';
struct2.b = rand(5);
struct1,struct2
struct1 = struct with fields:
a: 'first'
b: [1 2 3]
struct2 = struct with fields:
a: 'second'
b: [5x5 double]
Just as concatenating two scalar values such as [1,2] creates a 1-by-2 numeric array, concatenating
struct1 and struct2 creates a 1-by-2 structure array.
combined = [struct1,struct2]
combined=1×2 struct array with fields:
a
b
When you want to access the contents of a particular field, specify the index of the structure in the
array. For example, access field a of the first structure.
combined(1).a
ans =
'first'
Concatenation also applies to nonscalar structure arrays. For example, create a 2-by-2 structure
array named new. Because the 1-by-2 structure combined and the 2-by-2 structure new both have
two columns, you can concatenate them vertically with a semicolon separator.
new(1,1).a = 1;
new(1,1).b = 10;
new(1,2).a = 2;
new(1,2).b = 20;
new(2,1).a = 3;
new(2,1).b = 30;
new(2,2).a = 4;
new(2,2).b = 40;
larger = [combined; new]
larger=3×2 struct array with fields:
a
11 Structures
11-8
