Main Content

coder.loop.vectorize

R2026b

Vectorize for-loops in generated code

Since R2023a

    Description

    coder.loop.vectorize(loopID) prompts the code generator to transform the for-loop with index name loopID into vectorized operations in the generated code. To use this directive, you must enable the SIMD instruction set for your target hardware. See Leverage target hardware instruction set extensions.

    Using this directive can improve the performance of the generated code by processing multiple data elements per instruction. This directive works best for element-wise, independent operations that have relatively simple loop bodies. For more information about loop optimizations, see Optimize Loops in Generated Code.

    example

    Examples

    collapse all

    Examine the function vectorizeForLoops, which performs an addition operation on a matrix in a for-loop. The function uses the coder.loop.vectorize directive to vectorize the for-loop.

    function out = vectorizeForLoop(x,y) %#codegen
    out = ones(1,in);
    
    coder.loop.vectorize("i");
    for i = 1:100
        K = y+x;
        out(i) = out(i)+K;
    end
    end

    Generate a C static library for this function. Create a configuration object for a C static library and enable the SIMD instruction set by setting the InstructionSetExtensions property. This example uses "SSE2".

    cfg = coder.config("lib");
    cfg.InstructionSetExtensions = "SSE2";
    codegen -config cfg -report vectorizeForLoop -args {0,0}

    Open the code generation report and inspect the generated code. The generated function uses SIMD instructions inside the loop body to vectorize the operations.

    for (i = 0; i <= 98; i += 2) {
        _mm_storeu_pd(&out[i],
                      _mm_add_pd(_mm_loadu_pd(&out[i]), _mm_set1_pd(y + x)));
      }

    Input Arguments

    collapse all

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

    Limitations

    Tips

    • To view potential issues that the code generator encounters when applying the coder.loop.vectorize 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