Main Content

coder.loop.interchange

Interchange loop indices in generated code

Since R2023a

    Description

    example

    coder.loop.interchange("loopA_ID","loopB_ID") prompts the code generator to interchange the for loops with index names loopA_ID and loopB_ID in the generated code.

    Use this transform when accessing array elements stored in contiguous memory blocks. In such situations, the data is loaded into cache and can be reused without a cache refresh.

    For more information about loop optimizations, see Optimize Loops in Generated Code.

    loopObj = coder.loop.interchange(___) creates a loop control object with transformSchedule property set to coder.loop.interchange. Use the apply method to apply the transform to the specified loop.

    Examples

    collapse all

    You can use the coder.loop.interchange function to swap for loops in the generate code. This optimization can improve cache performance when accessing array elements in your code.

    Define a MATLAB® function interchangeForLoops that operates on a matrix by using two for-loops. Call the coder.loop.interchange function immediately before the for-loop to optimize.

    function out = interchangeForLoops()
    out = zeros(100,70);
    
    coder.loop.interchange('i','j');
    for i = 1:100
        for j = 1:70
            out(i,j) = out(i,j) + i*j;
        end
    end

    Generate code for this function by using the following command:

    codegen interchangeForLoopIndex -config:lib -launchreport

    Inspect the generated code in the code generation report. Notice that the for loops are swapped. The data elements are loaded into cache in a contiguous block and a larger portion of the cache is reused within the inner loop.

    void interchangeForLoopIndex(double out[7000])
    {
      int i;
      int j;
      memset(&out[0], 0, 7000U * sizeof(double));
      for (j = 0; j < 70; j++) {
        for (i = 0; i < 100; i++) {
          int out_tmp;
          out_tmp = i + 100 * j;
          out[out_tmp] += (double)((i + 1) * (j + 1));
        }
      }
    }

    Input Arguments

    collapse all

    for loop identifier or index name to interchange, specified as a character vector a string scalar.

    Data Types: char | string

    for loop identifier or index name to interchange, specified as a character vector a string scalar.

    Data Types: char | string

    Output Arguments

    collapse all

    Loop control object with transformSchedule property set to coder.loop.interchange.

    Version History

    Introduced in R2023a