Main Content

Define Scalar Structures for Code Generation

Restrictions When Defining Scalar Structures by Assignment

When you define a scalar structure by assigning a variable to a preexisting structure, you do not need to define the variable before the assignment. However, if you already defined that variable, it must have the same class, size, and complexity as the structure you assign to it. In the following example, p is defined as a structure that has the same properties as the predefined structure S:

...
S = struct('a',  0, 'b',  1, 'c',  2);
p = S;
...

Adding Fields in Consistent Order on Each Control Flow Path

When you create a structure, you must add fields in the same order on each control flow path. For example, the following code generates a compiler error because it adds the fields of structure x in a different order in each if statement clause:

function y = fcn(u) %#codegen
if u > 0
   x.a = 10;
   x.b = 20;
else
   x.b = 30;  % Generates an error (on variable x)
   x.a = 40;
end
y = x.a + x.b;

In this example, the assignment to x.a comes before x.b in the first if statement clause, but the assignments appear in reverse order in the else clause. Here is the corrected code:

function y = fcn(u) %#codegen
if u > 0
   x.a = 10;
   x.b = 20;
else
   x.a = 40;
   x.b = 30;
end
y = x.a + x.b;

Restriction on Adding New Fields After First Use

You cannot add fields to a structure after you perform the following operations on the structure:

  • Reading from the structure

  • Indexing into the structure array

  • Passing the structure to a function

For example, consider this code:

...
x.c = 10; % Defines structure and creates field c
y = x; % Reads from structure
x.d = 20; % Generates an error
...

In this example, the attempt to add a new field d after reading from structure x generates an error.

This restriction extends across the structure hierarchy. For example, you cannot add a field to a structure after operating on one of its fields or nested structures, as in this example:

function y = fcn(u) %#codegen

x.c = 10;
y = x.c;
x.d = 20; % Generates an error

In this example, the attempt to add a new field d to structure x after reading from the structure's field c generates an error.