Documentation

This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English verison of the page.

Note: This page has been translated by MathWorks. Please click here
To view all translated materals including this page, select Japan from the country navigator on the bottom of this page.

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 = 

  1x2 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 = 

  3x2 struct array with fields:

    a
    b

Access field a of the structure larger(2,1). It contains the same value as new(1,1).a.

larger(2,1).a
ans =

     1

Related Topics

Was this topic helpful?