Main Content

Generate Code with Parallel for-Loops (parfor)

This example shows how to generate C code for a MATLAB® algorithm that contains a parfor-loop.

  1. Write a MATLAB function that contains a parfor-loop. For example:

    function a = test_parfor %#codegen
    a=ones(10,256);
    r=rand(10,256);
    parfor i=1:10
      a(i,:)=real(fft(r(i,:)));
    end
  2. Generate C code for test_parfor. At the MATLAB command line, enter:

    codegen -config:lib test_parfor

    Because you did not specify the maximum number of threads to use, the generated C code executes the loop iterations in parallel on the available number of cores.

  3. To specify a maximum number of threads, rewrite the function test_parfor as follows:

    function a = test_parfor(u) %#codegen
    a=ones(10,256);
    r=rand(10,256);
    parfor (i=1:10,u)
      a(i,:)=real(fft(r(i,:)));
    end
  4. Generate C code for test_parfor. Use -args 0 to specify that the input, u, is a scalar double. At the MATLAB command line, enter:

    codegen -config:lib test_parfor -args 0 

    In the generated code, the iterations of the parfor-loop run on at most the number of cores specified by the input, u. If less than u cores are available, the iterations run on the cores available at the time of the call.

Related Topics