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):
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.