Different (pseudo) random numbers in parallel loops in Matlab

Querying random numbers in a parallel loop always returns the same pseudo-random numbers . How can i avoid this?

% workers initialization:
if matlabpool('size') == 0
    matlabpool('open',2);
else
    matlabpool('close');
    matlabpool('open',2);
end

% parallel loop always give the same random numbers...
parfor k = 1:10
    fprintf([num2str(rand(1,1)), ' ']);
end

One ideal solution would be to initialize a pseudo-random number generator in each thread according to processor time or the like. Things rng('shuffle')like don't seem to help here ...

console output:

Sending a stop signal to all the workers ... stopped.
Starting matlabpool using the 'local' profile ... connected to 2 workers.
0.32457 0.66182 0.63488 0.64968 
0.26459 0.096779 0.50518 0.48662 0.034895 0.85227 
+3
source share
1 answer

Here is the documentation of the various options. Here is one way to do something close.

numWorkers = matlabpool('size');
[streams{1:numWorkers}] = RandStream.create('mrg32k3a', ...
    'Seed', 'shuffle', 'NumStreams', numWorkers);
spmd
    RandStream.setGlobalStream(streams{labindex});
end

Or, to avoid creating all threads on the client, you can do this instead:

rng('shuffle'); % shuffle the client
workerSeed = randi([0, 2^32-1]);
spmd
    stream = RandStream.create('mrg32k3a', ...
        'Seed', workerSeed, ...
        'NumStreams', numlabs, ...
        'StreamIndices', labindex);
    RandStream.setGlobalStream(stream);
end
+3
source

All Articles