Main Content

coder.loop.interchange

R2026b

Interchange loop indices in generated code

Since R2023a

    Description

    coder.loop.interchange(loopA_ID,loopB_ID) directs the code generator to swap the nesting order of the for-loops with index names loopA_ID and loopB_ID in the generated code.

    Use this directive to improve memory locality if you access array elements stored in contiguous memory blocks. This directive can improve cache performance by enabling cache reuse without requiring a cache refresh.

    This directive can improve performance only when the current loop order results in a memory access pattern with poor locality. Use this directive for nested loops that have independent iterations and compatible bounds where reordering does not affect correctness.

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

    example

    Examples

    collapse all

    Use the coder.loop.interchange function to swap the nesting order of for-loops in the generated code.

    Examine the function interchangeForLoops. This function operates on a matrix by using two nested for-loops. It calls the coder.loop.interchange directive immediately before the outer for-loop.

    function out = interchangeForLoops %#codegen
    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 a C static library for this function.

    codegen -config:lib -report interchangeForLoops

    Open the code generation report and inspect the for-loops in the generated code. The code generator swaps the indices of the nested for-loops.

      for (j = 0; j < 70; j++) {
        for (i = 0; i <= 96; i += 4) {

    Input Arguments

    collapse all

    Index of the for-loop to interchange, specified as a string scalar or character vector.

    Index of the for-loop to interchange, specified as a string scalar or character vector.

    Tips

    • To view potential issues that the code generator encounters when applying the coder.loop.interchange directive, review the Code Insights section of the code generation report. See Code Generation Reports.

    Extended Capabilities

    expand all

    C/C++ Code Generation
    Generate C and C++ code using MATLAB® Coder™.

    GPU Code Generation
    Generate CUDA® code for NVIDIA® GPUs using GPU Coder™.

    Version History

    Introduced in R2023a