bzak
bzak

Reputation: 563

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:

Upvotes: 0

Views: 272

Answers (1)

Naveen
Naveen

Reputation: 306

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.

Upvotes: 1

Related Questions