MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

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

Concatenate Structures
Free download pdf