MATLAB: Generate the same random number stream with for and parfor loop

forparforrandom number

Dear all,
I have a question concerning random number generation. Is it possible to generate the same random number stream with a for and a parfor loop? Consider the following code example:
clear variables;
spmd
rng(0,'combRecursive');
end
seed = 5;
rng(seed);
for i = 1:4
r(:,i) = randn(4,1);
end
r
Executing this the result will be reproducably:
r = -0.6241 -0.7559 -1.1331 -0.5142
-0.0756 1.4777 0.1639 -1.3629
-0.2618 0.3802 -0.3092 -0.9377
-0.5144 -0.5975 0.0484 -0.2263
On the other hand, if I exchange for with parfor i will get(considering setting the random number generator to 5)
clear variables;
spmd
rng(5,'combRecursive');
end
seed = 5;
rng(seed);
parfor i = 1:4
r(:,i) = randn(4,1);
end
r
r =
-0.7559 -0.6241 -0.6241 -1.1331
1.4777 -0.0756 -0.0756 0.1639
0.3802 -0.2618 -0.2618 -0.3092
-0.5975 -0.5144 -0.5144 0.0484
How can I configure the random number generator in such a way, that parfor and for will give the same random numbers? I did read the documentation in:
but unfortunately was not able to achieve this.
Thank you very much. Kind regards,

Best Answer

You can't, because the parfor execution order is not specified.
The easiest way to avoid this problem would be to generate all random numbers before the loop, and then use indexing to pick the appropriate slice within each iteration.