This section shows how to modify a simple for-loop so that it runs in parallel. This loop does not have a lot of iterations, and it does not take long to execute, but you can apply the principles to larger loops. For these simple examples, you might not notice an increase in execution speed.

  1. Suppose your code includes a loop to create a sine wave and plot the waveform:

    for i=1:1024
        A(i) = sin(i*2*pi/1024);
        end
        plot(A)
  2. To interactively run code that contains a parallel loop, you first open a MATLAB pool. This reserves a collection of MATLAB worker sessions to run your loop iterations. The MATLAB pool can consist of MATLAB sessions running on your local machine or on a remote cluster:

    matlabpool open local 3
  3. With the MATLAB pool reserved, you can modify your code to run your loop in parallel by using a parfor statement:

    parfor i=1:1024
        A(i) = sin(i*2*pi/1024);
        end
        plot(A)

    The only difference in this loop is the keyword parfor instead of for. After the loop runs, the results look the same as those generated from the previous for-loop.

    Because the iterations run in parallel in other MATLAB sessions, each iteration must be completely independent of all other iterations. The worker calculating the value for A(100) might not be the same worker calculating A(500). There is no guarantee of sequence, so A(900) might be calculated before A(400). (The MATLAB Editor can help identify some problems with parfor code that might not contain independent iterations.) The only place where the values of all the elements of the array A are available is in the MATLAB client, after the data returns from the MATLAB workers and the loop completes.

  4. When you are finished with your code, close the MATLAB pool and release the workers:

    matlabpool close

For more information on parfor-loops, see Parallel for-Loops (parfor).