Documentation Center

  • Trial Software
  • Product Updates

Define Arrays of Structures for Code Generation

Ensuring Consistency of Fields

When you create an array of MATLAB® structures with the intent of generating code, you must be sure that each structure field in the array has the same size, type, and complexity.

Once you have created the array of structures, you can make the structure fields variable-size using coder.varsize. For more information, see Declare a variable-size structure field..

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 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 Concatenating 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;
...
Was this topic helpful?