Main Content


Disable automatic parallelization of a for loop



    coder.loop.parallelize('never') disables automatic parallelization of the for loop placed immediately after it. This pragma overrides the EnableAutoParallelization configuration setting.

    This pragma supports explicit for loops only. For more information on explicit and implicit loops, see Parallelize Implicit for Loops.


    collapse all

    This example shows how to disable the automatic parallelization of a specific for loop in your MATLAB® code by using the coder.loop.parallelize('never') directive.

    Define the MATLAB function autoparExample:

    function [x, y] = autoparExample(x, y) %#codegen
    x = x * 17;
    % Pragma to disable automatic parallelization of for-loops
    for i = 10:numel(x)
        y(i) = sqrt(y(i));

    This function contains two loops:

    • The mtimes (matrix multiplication) function contains an implicit for loop that iterates over the elements of the matrix x.

    • The explicit for loop that calculates the square root of a subset of the elements of the matrix y. The coder.loop.parallelize('never') directive disables automatic parallelization of this loop.

    Create a code generation configuration object for a static library. Set the EnableAutoParallelization property to true. Specify the input types as 1-by-2000 row vectors of doubles and generate code.

    cfg = coder.config('lib');
    cfg.EnableAutoParallelization = 1;
    codegen -config cfg autoparExample -args {rand(1,2000) rand(1,2000)} -report
    Code generation successful: View report

    Open the code generation report and inspect the generated autoparExample function:

    • The generated code contains a parallel loop for the multiplication operation.

    • The explicit for loop is converted to a serial loop in the generated code. This loop was preceded by the coder.loop.parallelize('never') directive in your MATLAB code. The code generator did not parallelize it.

    void autoparExample(double x[2000], double y[2000])
      int b_i;
      int i;
      if (!isInitialized_autoparExample) {
    #pragma omp parallel for num_threads(omp_get_max_threads()) private(i)
      for (i = 0; i < 2000; i++) {
        x[i] *= 17.0;
      /*  Pragma to disable automatic parallelization of for-loops */
      for (b_i = 0; b_i < 1991; b_i++) {
        y[b_i + 9] = sqrt(y[b_i + 9]);

    Extended Capabilities

    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 R2021a