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 structureS
:
... 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 structurex
in a different order in eachif
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 tox.a
comes beforex.b
in the firstif
statement clause, but the assignments appear in reverse order in theelse
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 fieldd
after reading from structurex
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 fieldd
to structurex
after reading from the structure's fieldc
generates an error.