matlabrandom-seedmodular-design

Seeding in MATLAB with rng with parfor


Suppose I have the following code in MATLAB:

clc; clear;
myseed = rng(1);
c = 1; d = 2;
parfor i = 1:1000
   a = randn(200,1);
   b = randn(50,1);
   c*(sum(a)+sum(b));
end
parfor i = 1:1000
   a = randn(200,1);
   b = randn(50,1);
   d*(sum(a)+sum(b));
end

The third line in each loop above captures the processing that I apply to a and b, which is specific to the loop and which is very lengthy in my real application. The reason for repeating the randomizing of a and b is because I would like to put these 2 loops into 2 separate files that I can call from the main program. I understand there is some inefficiency here but the code would be easier to follow for me.

How do I use rng so a and b in one loop are the same as the a and b in another loop? (That is, the 1000 "random" values for a from the first loop are the same as the 1000 "random" values for a from the other loop. They don't have to be in the same order.) I tried adding rng(myseed) between the 2 loops but this didn't help.


Solution

  • I don't use parfor often, but the following approach (adapted from here) seems to work:

    parpool('local',4); % create parallel pool of workers
    spmd
        rng(123); % set the same seed in each worker
    end
    parfor k = 1:12
        r = rand; % generate a random number
        w = getCurrentWorker;
        fprintf('Worker %i, iteration %i, random number %f\n', w.ProcessId, k, r)
    end
    

    Note how each worker generates the same random numbers in the same order. (The iterations are randomly assigned to workers, and are run in a random order; this is by design).

    Starting parallel pool (parpool) using the 'local' profile ...
    connected to 4 workers.
    Worker 11688, iteration 1, random number 0.275141
    Worker 17188, iteration 2, random number 0.275141
    Worker 18408, iteration 4, random number 0.275141
    Worker 18408, iteration 3, random number 0.423046
    Worker 5812, iteration 6, random number 0.275141
    Worker 5812, iteration 5, random number 0.423046
    Worker 11688, iteration 8, random number 0.423046
    Worker 11688, iteration 7, random number 0.973406
    Worker 17188, iteration 9, random number 0.423046
    Worker 18408, iteration 10, random number 0.973406
    Worker 5812, iteration 11, random number 0.973406
    Worker 17188, iteration 12, random number 0.973406