以下代码生成具有给定成功概率的随机数:
n=[randi([0 1],1,8) ones(1,8)];
n= n(randperm(10));
如果重复上述行,则会生成随机(不可抑制的)值:
这是第一次运行的n:
n = 1 0 1 0 0 1 1 1 1 1
这是第二次运行的n:
n = 1 1 1 0 1 1 1 1 1 1
如何让发电机以更高的概率选择已经选择为故障(0)的数量?
这就是第二轮中2,3和4人有更多失去概率的概率。这并不意味着他们必须失败。
条目1到10是10个不同的用户输出。
好吧,让我们说总是最多30%的条目将是0.每次执行上述操作。然而,这是随机完成的。因此,10个中任何3个中的最大值都可以为零。
我不希望改变成功的概率。只需控制哪一个为零。
进一步澄清我想要的:如果3将被“随机”选为零,那么让之前选择的三个被选中的概率更高,而不是被选中。
答案 0 :(得分:1)
以下是具有以下逻辑的解决方案:
请注意,我认为同样可能有0,1,2或3次失败。
nRuns = 5;
allRuns = zeros(nRuns,10); %# stores success and failure for all runs
%# (1) generate from 0 to 3 failures (each outcome is equally likely)
nFailures = randi([0 3],1);
tmp = randperm(10);
firstRun = tmp > nFailures
allRuns(1,:) = firstRun;
%# (2) decide how many failures occur in the 2nd run (each outcome is equally likely)
for iRun = 2:nRuns
%# as the loop has been added later
%# I use "2" to indicate any next run
nFailures2 = randi([0 3],1);
%# (3) give previous failures a higher chance to fail again
failIdx = find(~allRuns(iRun-1,:));
successIdx = find(allRuns(iRun-1,:));
%# 5x higher chance of failing for previous failures
failCandidates = [repmat(failIdx,1,5),successIdx];
failCandidatesRand = failCandidates(randperm(length(failCandidates)));
%# if you have R2012a or later
failCandidatesRand = unique(failCandidatesRand ,'stable');
toFail = failCandidatesRand (1:nFailures2);
%# alternatively, if you have R2011b or earlier
toFail = zeros(nFailures2,1);
toFail(1) = failCandidatesRand(1);
ii = 2;
kk = 2;
while ii < (nFailures2+1)
if ~any(toFail==failCandidatesRand(kk));
toFail(ii) = failCandidatesRand(kk);
ii = ii + 1;
end
kk = kk + 1;
end
%# write failures
nextRun= true(1,10);
nextRun(toFail) = false
allRuns(iRun,:) = nextRun;
end
答案 1 :(得分:0)
也许你想要这样的东西:
n1 = rand(1, 8) > 0.5;
n2 = rand(1, 8) > (n1 * 0.5 + ~n1 * 0.6);
这将生成具有相同概率的第一组0和1。对于n2,如果n1中的对应值为1,那么有50%的概率为0或1.如果n1中的对应值为0,那么有60%的概率为0.
感谢您澄清问题。让我们再试一次! 我认为您可以使用randsample。它有点乱,因为似乎没有替代加权采样的选项。
N = ones(1, 10);
for round=1:10
failures = randi([1, 3]);
indices = [];
while (numel(unique(indices)) < failures)
indices = randsample(10, failures, true, [N + ~N*1.1]);
end
N = ones(1, 10);
N(indices) = 0;
disp(N);
end