Main Content

Define Arrays of Structures for Code Generation

Ensuring Consistency of Fields

For code generation, when you create an array of MATLAB® structures, corresponding fields in the array elements must have the same size, type, and complexity.

Once you have created the array of structures, you can make the structure fields variable-size by using coder.varsize. See Declare Variable-Size Structure Fields.

Using repmat to Define an Array of Structures with Consistent Field Properties

You can create an array of structures from a scalar structure by using the MATLAB repmat function, which replicates and tiles an existing scalar structure:

  1. Create a scalar structure, as described in Define Scalar Structures for Code Generation.

  2. Call repmat, passing the scalar structure and the dimensions of the array.

  3. Assign values to each structure using standard array indexing and structure dot notation.

For example, the following code creates X, a 1-by-3 array of scalar structures. Each element of the array is defined by the structure s, which has two fields, a and b:

...
s.a = 0;
s.b = 0;
X = repmat(s,1,3);
X(1).a = 1;
X(2).a = 2;
X(3).a = 3;
X(1).b = 4;
X(2).b = 5;
X(3).b = 6;
...

Defining an Array of Structures by Using struct

To create an array of structures using the struct function, specify the field value arguments as cell arrays. Each cell array element is the value of the field in the corresponding structure array element. For code generation, corresponding fields in the structures must have the same type. Therefore, the elements in a cell array of field values must have the same type.

For example, the following code creates a 1-by-3 structure array. For each structure in the array of structures, a has type double and b has type char.

s = struct('a', {1 2 3}, 'b', {'a' 'b' 'c'});

Defining an Array of Structures Using Concatenation

To create a small array of structures, you can use the concatenation operator, square brackets ( [ ] ), to join one or more structures into an array. See Creating, Concatenating, and Expanding Matrices. For code generation, the structures that you concatenate must have the same size, class, and complexity.

For example, the following code uses concatenation and a local function to create the elements of a 1-by-3 structure array:

...
W = [ sab(1,2) sab(2,3) sab(4,5) ];

function s = sab(a,b)
  s.a = a;
  s.b = b;
...

See Also

(Simulink)

Related Topics