如何生成具有给定概率和约束的随机数? [英] How to generate random numbers with given probability and constraints?

查看:160
本文介绍了如何生成具有给定概率和约束的随机数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

N.B:这不是我上一个问题的重复,因为我添加了约束!

N.B: This is not a duplication of my last question because I added constraints!

我想以给定的概率生成一个介于1到100之间的随机数的矩阵A(40x10000):

I want to generate a matrix A(40x10000) of random number between 1 and 100 with a given probability:

p1=Prob(1)     (chance of 1)
p2=Prob(2)     (chance of 2)
 ... 
p100=Prob(100)  (chance of 100)

和约束:V1,V2,...,V20是包含1到100之间的4个元素的向量.矩阵A的每个列向量应包含这20个向量中的每个向量中的至少一个元素. V1, ..., V20是具有已知元素的预定义向量.

and constraints: V1,V2,...,V20 are vectors containing 4 elements between 1 and 100. Each column vector of the matrix A should contain at least one element of each of these 20 vectors. V1, ..., V20 are predefined vectors with known elements.

例如,如何修改以下程序以添加最后一个约束:

for example, how to modify the following program to add the last constraint:

h = 40; w = 10000;
A = reshape( randsample( numel(Prob), h*w, true, Prob ), [h w] );

更多详细信息:

  • 每个A(:,i) {i=1,..,10000}对于所有k=1,..,20都应包含Vk(1) or Vk(2) or Vk(3) or Vk(4). A(:,i)必须包含每个Vk中的至少一个值,但它将尊重概率并且不会生成重复值.如果ViVj的某些值相等,则A(:,k)可能只有一个元素同时验证ViVj约束.

  • each A(:,i) {i=1,..,10000} should contain Vk(1) or Vk(2) or Vk(3) or Vk(4) for all k=1,..,20. A(:,i) must contain at least one value from every Vk, but that it will respect the probabilities and does not generate duplicate values. If some values of Vi and Vj are equal, A(:,k) could have a single element validating both Vi and Vj constraints.

例如:如果V1=[6 87 1 56]A(:,i)应该包含6或87或1或56,但是A(:, i)可以包含(6和1)或(6和1和87)或...

for example: if V1=[6 87 1 56], A(:,i) should contain 6 or 87 or 1 or 56 but A(:, i) may contain (6 and 1) or (6 and 1 and 87) or ...

推荐答案

以下是一种解决方案:

h=40;
w=10000;
output=zeros(h,w);
i=1;
while i<=w
temp=randsample(numel(prob),h,true,prob);
check=all(any(ismember(vec,temp)));
if check~=0
output(:,i)=temp;
i=i+1;
end
end

不幸的是,生成具有指定约束条件的矩阵大约需要4分钟.欢迎使用其他耗时更少的解决方案.

Unfortunately, this takes approximately 4 minutes to generate the matrix with the specified constraints. Any other solution which takes less time is welcome.

这篇关于如何生成具有给定概率和约束的随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆