Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
819 views
in Technique[技术] by (71.8m points)

matlab - How to generate random numbers with given probability and constraints?

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

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)

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] );

more details:

  • 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.

  • 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 ...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is one solution:

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...