Main Content

Working with parfor

How Statistical Functions Use parfor

parfor is a Parallel Computing Toolbox™ function similar to a for loop. Parallel statistical functions call parfor internally. parfor distributes computations to worker processors.

Diagram of the workflow when using parfor. When using a parfor loop indexed from 1 to n, the software distributes the lines of code to 1 through n workers. The results are then returned to the client.

Characteristics of parfor

You might need to adjust your code to run in parallel, for example, you need independent loops and the workers must be able to access the variables. For advice on using parfor, see Parallel for-Loops (parfor) (Parallel Computing Toolbox).

No Nested parfor Loops

parfor does not work in parallel when called from within another parfor loop, or from an spmd block. Parallelization occurs only at the outermost level.

Suppose, for example, you want to apply jackknife to your function userfcn, which calls parfor, and you want to call jackknife in a loop. The following figure shows three cases:

  1. The outermost loop is parfor. Only that loop runs in parallel.

  2. The outermost parfor loop is in jackknife. Only jackknife runs in parallel.

  3. The outermost parfor loop is in userfcn. userfcn uses parfor in parallel.

When parfor Runs in Parallel

Illustration of the three cases of using parfor

For help converting nested loops to use parfor, see Convert for-Loops Into parfor-Loops (Parallel Computing Toolbox).

See also Quick Start Parallel Computing for Statistics and Machine Learning Toolbox™.