0

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?

Sara
  • 2,308
  • 11
  • 50
  • 76
  • just recalled it might be a possible duplicate of [Random numbers that add to 100: Matlab](http://stackoverflow.com/questions/8064629/random-numbers-that-add-to-100-matlab) – bla Jan 04 '13 at 23:07

3 Answers3

4

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.

Leonid Beschastny
  • 50,364
  • 10
  • 118
  • 122
2

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

bla
  • 25,846
  • 10
  • 70
  • 101
0

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.

Bohemian
  • 412,405
  • 93
  • 575
  • 722