Documentation Center

  • Trial Software
  • Product Updates

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

Just as concatenating two scalar values such as [1, 2] creates a 1-by-2 numeric array, concatenating struct1 and struct2,

combined = [struct1, struct2]

creates a 1-by-2 structure array:

combined = 
    1x2 struct array with fields:

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:


This code returns

ans =

Concatenation also applies to nonscalar structure arrays. For example, create a 2-by-2 structure array named new:

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;

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:

larger = [combined; new]

This code returns a 3-by-2 structure array,

larger = 
    3x2 struct array with fields:

where, for example,

larger(2,1).a =

For related information, see:

Was this topic helpful?