Main Content

coder.loop.vectorize

Vectorize for loops in generated code

Since R2023a

    Description

    coder.loop.vectorize("loopID") prompts the code generator to vectorize the for loop with index name loopID in the generated code.

    The generated code uses the SIMD instruction set for your target hardware in the generated code. Set the InstructionSetExtensions property in your code configuration object according to your hardware requirements to apply this transform.

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

    example

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

    Examples

    collapse all

    You can use the coder.loop.vectorize function to apply a vectorize transform to a for loop in the generated code.

    Define a MATLAB® function that performs in an addition operation on a matrix within a for loop. Call the coder.loop.vectorize function immediately before the for-loop in your function.

    function out = vectorizeForLoops(x,y)
    out = initRow(100);
    
    coder.loop.vectorize("i");
    for i = 1:100
        K = y+x;
        out(i) = out(i) + K;
    end
    end
    
    function out = initRow(in)
    coder.inline('never');
    out = ones(1,in);
    end

    To generate code with vectorized for-loops, create a configuration object whose InstructionSetExtensions property is set according to your target processor. For more information, see Generate SIMD Code from MATLAB Functions for Intel Platforms.

    For an Intel® processor, generate code for this function by running the following command:

    cfg = coder.config('lib');
    cfg.InstructionSetExtensions = "SSE2";
    codegen vectorizeForLoops -config cfg -args {0,0} -launchreport

    Inspect the generated code in the code generation report. Notice that the generated code uses an SIMD instruction set to carry out the operations.

    void vectorizeForLoops(double x, double y, double out[100])
    {
      int i;
      initRow(out);
      for (i = 0; i <= 98; i += 2) {
        __m128d r;
        r = _mm_loadu_pd(&out[i]);
        _mm_storeu_pd(&out[i], _mm_add_pd(r, _mm_set1_pd(y + x)));
      }
    }
    static void initRow(double out[100])
    {
      int i;
      for (i = 0; i < 100; i++) {
        out[i] = 1.0;
      }
    }

    Input Arguments

    collapse all

    for loop identifier or index name to vectorize, 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.vectorize.

    Version History

    Introduced in R2023a