Main Content

Simplify Multiply Operations for Array Indexing in Loops

If you use Embedded Coder® to generate C/C++ code from MATLAB® code, you can enable an optimization that simplifies array indexing in loops in the generated code. When possible, for array indices in loops, this optimization replaces multiply operations with add operations. Multiply operations can be expensive. This optimization, referred to as strength reduction, is useful when the C/C++ compiler on the target platform does not optimize the array indexing.

Here is code generated without the optimization.

for (i = 0; i < 10; i++) {
    z[5 * (1 + i) - 1] = x[5 * (1 + i)];

Here is code generated with the optimization.

int i = 0;
for (k = 0; k < 10; k++) {
    z[i + 4] = x[i + 5];
    i += 5;

The variable names used in these code snippets can differ from what you see in the generated code, as the code surrounding the snippets can affect the variable names used by the code generator.

By default, the strength reduction optimization is disabled. To enable it:

  • At the command line, set the configuration object parameter EnableStrengthReduction to true.

  • In the MATLAB Coder™ app, project build settings, on the All Settings tab, set Simplify array indexing to Yes.

Even when the optimization replaces the multiply operations in the generated code, it is possible that the C/C++ compiler can generate multiply instructions.

Related Topics