Main Content

Best Practices for Defining Variables for C/C++ Code Generation

If you want to generate code from a MATLAB Function block, the MATLAB® code in the block must comply with the C/C++ code generation requirements. Some coding practices that work in MATLAB code do not work when generating code. Follow these best practices to optimize your code and avoid simulation errors.

Explicitly Define Variables Before Using Them

For C/C++ code generation, you must explicitly define variable values and properties before using them in operations or returning them as outputs. Doing this prevents errors that occur when you do not define the variable.

Note

When you define variables, they are local by default and do not persist between function calls. To make variables persistent, use the persistent function.

Define Variables on All Execution Paths

You must define a variable on all execution paths, such as execution paths dictated by if statements. Consider this MATLAB code that defines a variable before using it as an input to a function:

...
if c <= 0
  x = 11;
end
% Later in your code ...
if c > 0
% Use x in the function foo
  foo(x);
end
...
The code assigns x to a value only if c <= 0 and uses x only when c > 0. Depending on the value for c, this code can work in MATLAB without errors. However, code generation fails when you try to generate C/C++ code from this MATLAB code, because the code generator detects that x is undefined on the execution path when c > 0.

To make this code suitable for code generation, define x before using it:

x = 0;
...
if c <= 0
  x = 11;
end
% Later in your code ...
if c > 0
% Use x in the function foo
  foo(x);
end
...

Define All Structure Fields

You must also define each structure field for all execution paths. Consider this MATLAB code:

...
if c > 0 
  s.a = 11;
  disp(s);
else
  s.a = 12;
  s.b = 12;
end
% Use s in the function foo
foo(s);
...
The first part of the if statement uses only the field a, and the else statement uses the fields a and b. This code works in MATLAB but generates a compilation error during C/C++ code generation. To prevent this error, do not add fields to a structure after you use the structure. For more information, see Structure Definition for Code Generation.

To make this code suitable for C/C++ code generation, define the fields of s before using them:

...
% Define fields in structure s
s = struct("a", 0, "b", 0);
if c > 0 
  s.a = 11;
  disp(s);
else
  s.a = 12;
  s.b = 12;
end
% Use s in the function foo
foo(s);
...

Use Caution When Reassigning Variable Properties

You can reassign certain variables after the initial assignment with a value of different class, size, or complexity. See Reassignment of Variable Properties. However, if you reassign the variable type after the initial assignment, the code often returns a compilation error during code generation. In general, assign each variable a specific class, size, type, and complexity.

Define Variable Numeric Data Types

double is the default numeric data type in MATLAB. To define variables of other data types, you must explicitly define the data type in the definition with the correct prefix or operator. Be mindful of the data types you use, because using variables assigned to different data types in your code can cause type mismatch errors.

For example, this code defines the variable x as a double and y as an 8-bit integer:

x = 15;
y = uint8(x);

For more information on supported types in MATLAB, see Numeric Types.

Define Matrices Before Assigning Indexed Variables

Growing a variable by writing an element beyond its current size results in a compile-time or run-time error, unless you use end + 1 indexing or otherwise first define the variable as variable-size. See Generate Code for Growing Arrays and Cell Arrays with end + 1 Indexing (MATLAB Coder) and Define Variable-Size Data for Code Generation. You can also specify output variables as variable size in the Symbols pane and Property Inspector. See Declare Variable-Size MATLAB Function Block Variables. To avoid size-related errors without using end + 1 indexing or defining arrays as variable-size, define the maximum size of the array before assigning values to its elements.

For example, this assignment results in an error at code generation time:

g = zeros(3,3);
g(5,2) = 14.6;

Correct this code by defining matrix g of sufficient size:

g = zeros(5,5);
g(5,2) = 14.6;

For more information about indexing matrices, see Incompatibility with MATLAB in Matrix Indexing Operations for Code Generation.

Aim to Index Arrays by Using Fixed-Size Vectors

Although code generation supports variable-size arrays, variable-size arrays require additional memory, which can slow performance. When possible, use constant-value vectors to index arrays. For example:

...
% extract 7 elements from A using a constant-value vector
B = A(1:7);
...
In this example, the code generator recognizes that B is of fixed-size.

If you index into an array using the colon operator and variable values, the code generator does not always correctly determine whether the array is fixed-size or variable-size. For example, both of the following arrays are fixed-size, independent of the value of i:

...
% extract 7 elements from A using a fixed-size vector
B = A(i-1:i+5);
C = A(-1+2*i:5+2*i);
...
When the value of i is known at code generation time, the code generator recognizes both B and C as fixed-size arrays. However, when the value of i is unknown at code generation time, the code generator recognizes B as fixed-size but defines C as variable-size. As a result, you can aim to define an array that does not change size and should therefore be fixed-sized, but the code generator interprets and specifies the array as variable-sized.

In some such cases, it is possible to rewrite your MATLAB code to force the code generator to recognize that the defined array does not change size. For example, you can rewrite the definition of C above to extract the array indexing expression from the mathematical operations involving the variable (i) that is unknown at code generation time:

...
% extract 7 elements from A using a fixed-size vector
C = A(2*i+(-1:5));
...
After this rewrite, the code generator recognizes C as a fixed-size array.

In some other code patterns, the array indices include variables that affect the array size, but these variables are known at compile time. In these situations, the extracted array is actually fixed-size, but the code generator might fail to identify it as such and treat it as variable-size. Occasionally, you can also rewrite such code to generate fixed-size arrays. In this example, the arrays D_varSize and D_fixSize are identical. However, the code generator defines D_varSize as variable-size and D_fixSize as fixed-size:

...
width = 25;              
D_varSize = A(i-width:i+width);  % D_varSize is variable-size if i is unknown at compile time 
D_fixSize = A(i+(-width:width)); % D_fixSize is fixed-size whether or not i is unknown at compile time
...

See Also

| |

Related Topics