Main Content

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

If you want to generate code from a MATLAB Function block, you must ensure the MATLAB® code in the block complies 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 the variable is not defined.

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, the MATLAB code generates a compilation error when you generate C/C++ code from it 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 Fields in a Structure

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 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, as described in 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. You must define the array before assigning values to its elements.

The only situation in which code generation supports growing arrays via indexing is when you use end + 1. See Generate Code for Growing Arrays and Cell Arrays with end + 1 Indexing (MATLAB Coder).

For example, this assignment results in an error:

g(3,2) = 14.6;

Correct this code by defining the matrix with a specific size first.

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

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

You can grow the size of variables if you define the variable as variable size first. You can also specify output variables as variable size in the Symbols pane and Property Inspector. See Define Variable-Size Data for Code Generation and Declare Variable-Size MATLAB Function Block Variables.

Index Arrays by Using Constant Value Vectors

Although code generation can support variable size arrays, variable size arrays requires additional memory, which can slow performance. When possible, use constant value vectors as you index arrays.

If you need to index through an array, be careful when using the colon operator. In some cases the code generator does not correctly determine whether an array indexed with a the colon operator is fixed size or variable size. As a result, you may define an array that does not change size, and should therefore be fixed-sized, but the code generator specifies the array as variable-sized.

For example, this code creates the array out by using the variable i indexed through the random row vector A:

...
% extract elements -1+2*i through 5+2*i for processing
A = rand(1,10);
out = A(-1+2*i:5+2*i);

In this example, A is always the same size. If i is a compile-time constant value, the code generator produces a fixed size object for out. If i is unknown at compile time, the code generator produces a variable size array for out.

By contrast, this example produces a fixed-sized array if i is known or unknown at compile time:

...
%  extract elements i through 2+i for processing
A = rand(1,10);
out = A(i:2+i);

Occasionally, you can rewrite code to generate fixed size arrays. In this example, the first array is variable-sized, and second is fixed-sized, despite both producing the same array:

...
width = 25;              
A = A(j-width:j+width);  % A is variable-size, if j is unknown at compile time 
fsA = A(j+(-width:width)); % This makes A fixed-size, even if j is unknown at compile time
...

See Also

|

Related Topics