Matlab:在每个parfor循环中生成不同的随机数

Matlab: Generating different random numbers in each parfor loop

我有如下一段代码:

nruns=100
nloops=2
zz=zeros(nloops,nruns);

for wLoop=1:nloops
delete(gcp('nocreate'));
parpool(npools);
parfor wRun=1:nruns
zz(wLoop,wRun)=rand
end
end
disp('done')

size(unique(zz))

每次池关闭并重新打开时,似乎种子都会重新初始化为其默认值,因此我得到的不同数字比预期的 nruns*nloops 少得多。 如果我添加

,此行为不会改变
rng('shuffle','combRecursive')

在 parfor 内部或之前。 如果我不在每次迭代时关闭池,则没有问题,但是对于我想到的用法,每次迭代都需要使用不同的池。 如何在 parfor 循环的每次迭代中获得真正不同的随机数?

首先,现有行为记录在此处:https://uk.mathworks.com/help/distcomp/control-random-number-streams.html。 (请注意,这与 MATLAB 本身基本相同——它始终以完全确定的随机数生成器状态启动——尽管 parfor 循环中的迭代实际上并不是确定性地调度的)。

要回答您的问题 - 您可以采用概述的方法 in this doc page。这是一种方法:

% Shuffle the state at the client
rng('shuffle');
% Pick an offset
streamOffset = randi(10000);

out = zeros(10);
for idx = 1:10
    parfor jdx = 1:10
        setupRandStream(idx + streamOffset, jdx);
        out(idx, jdx) = rand;
    end
end

% Set up the global random number state to the specific stream
% and substream using combined recursive generator.
function setupRandStream(stream, substream)
s = RandStream.create('mrg32k3a', 'NumStreams', stream, ...
    'StreamIndices', stream);
s.Substream = substream;
RandStream.setGlobalStream(s);
end