Assign Values to Structures and Fields - MATLAB & Simulink (original) (raw)

Main Content

When assigning values to a structure, substructure, or field for code generation, use these guidelines:

Field properties must be consistent across structure-to-structure assignments

If: Then:
Assigning one structure to another structure. Define each structure with the same number, type, and size of fields.
Assigning one structure to a substructure of a different structure and vice versa. Define the structure with the same number, type, and size of fields as the substructure.
Assigning an element of one structure to an element of another structure. The elements must have the same type and size.

For structures with constant fields, do not assign field values inside control flow constructs

In the following code, the code generator recognizes that the structure fields s.a and s.b are constants.

function y = mystruct() s.a = 3; s.b = 5; y = zeros(s.a,s.b);

If a field of a structure is assigned inside a control flow construct, the code generator does not recognize that s.a and s.b are constant. Consider the following code:

function y = mystruct(x) s.a = 3; if x > 1 s.b = 4; else s.b = 5; end y = zeros(s.a,s.b);

If variable-sizing is enabled, y is treated as a variable-size array. If variable-sizing is disabled, y, the code generator reports an error.

Do not assign mxArrays to structures

You cannot assign mxArrays to structure elements; convert mxArrays to known types before code generation (see Working with mxArrays).

Do not assign handle classes or sparse arrays to global structure variables

Global structure variables cannot contain handle objects or sparse arrays.