简体   繁体   中英

Matlab function for creating random number satisfying constraints

As an input I have two number x and y. x>y . I want to create exactly y non-zero random number which their sum will be equal to x . I know randi([min max]) function . Can you help me?

If I got it right, you want something like this:

data = rand(1,y);
data = data * x / sum(data);

data will contain exactly y positive uniformly distributed numbers which sum equals to x .

Check out the file random vectors generator with fixed sum in Matlab FEX. I believe this will answer your question.

Leonid's approach will certainly generate a set of random numbers that have the correct sum, but it won't select uniformly over the allowed space. If this is important, an approach that will work is the following:

(with x = 1):

  1. Generate Y-1 random numbers uniformly over [0,1].
  2. Sort the Y-1 numbers from smallest to largest. Call these {y1,...,y_{N-1}}
  3. Take as the Y random numbers the set {y_1-0 ,y_2-y1,...,1-y_{N-1}} == {n_1,... n_Y}.

These n_i clearly sum to one. It is easy to prove uniformity by considering the probability for a given realization of the n_i.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM