Main Content


Vectorize for loops in generated code

Since R2023a



    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.

    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.


    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);
    for i = 1:100
        K = y+x;
        out(i) = out(i) + K;
    function out = initRow(in)
    out = ones(1,in);

    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;
      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