Main Content

coder.loop.unrollAndJam

Unroll and jam for-loops in the generated code

Since R2023a

    Description

    example

    coder.loop.unrollAndJam("loopID",unrollFactor) prompts the code generator to unroll and jam the loop with index name loopID by a factor specified by unrollFactor in the generated code.

    Unroll and jam transforms are usually applied to perfectly nested loops, or where all the data elements are accessed within the inner loop. This transform unrolls the body of the inner loop according to the loop index of the outer loop.

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

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

    Examples

    collapse all

    You can use the coder.loop.unrollAndJam function to apply an unroll and jam transform on a for-loop in the generated code.

    Define a MATLAB® function unrollAndJamTransform that performs operations on a matrix.

    function out = unrollAndJamTransform
    out = zeros(10);
    
    coder.loop.unrollAndJam("i",5);
    for i = 1:10
        for j = 1:10
            out(i,j) = out(i,j) + local(i,j);
        end
    end
    end
    
    function y = local(x,z)
    coder.inline('never');
    y = x^2 + z^2;
    end

    Generate code for this function by running the following command:

    codegen unrollAndJamTransform -config:lib -launchreport

    Inspect the generated code for the function in the code generation report. Notice that the first loop is unrolled and subsequent operations are performed in the inner loop. This helps keep the array in cache to be reused.

    void unrollAndJamTransform(double out[100])
    {
      int i;
      int j;
      memset(&out[0], 0, 100U * sizeof(double));
      for (i = 0; i <= 5; i += 5) {
        for (j = 0; j < 10; j++) {
          int out_tmp;
          out_tmp = i + 10 * j;
          out[out_tmp] += local((double)i + 1.0, (double)j + 1.0);
          out[out_tmp + 1] += local(((double)i + 1.0) + 1.0, (double)j + 1.0);
          out[out_tmp + 2] += local(((double)i + 2.0) + 1.0, (double)j + 1.0);
          out[out_tmp + 3] += local(((double)i + 3.0) + 1.0, (double)j + 1.0);
          out[out_tmp + 4] += local(((double)i + 4.0) + 1.0, (double)j + 1.0);
        }
      }
    }
    static double local(double x, double z)
    {
      return x * x + z * z;
    }

    Input Arguments

    collapse all

    for loop identifier or index name to unroll and jam, specified as a character vector a string scalar.

    Data Types: char | string

    Factor by which loop is unrolled in the generated code, specified as a numeric value.

    Output Arguments

    collapse all

    Loop control object with transformSchedule property set to coder.loop.unrollAndJam.

    Version History

    Introduced in R2023a