MATLAB: Random positive numbers with constant sum

random

How to form a matrix such that every time the numbers add up to be the same
z=0.4
minimum z= 0.2
maximum z= 0.6
R is a random number between 0.2 and 0.6
a 1x10 R matrix is generated but the sum must be equal to (0.4 x 10 = 4)
I tried running the following using randn but it gives negatives numbers and the sums are not constant
z=0.4
zmax=1.5*z;
zmin=0.5*z;
R=zmin+randn(1,10)*(zmax-zmin);
Eg. Desired random number R matrix
[0.35 0.27 0.43 0.51 0.54 0.44 0.37 0.29 0.59 0.21]
sum(R)=4 < must be consistent for every matrix generated

Best Answer

First of all, there is no such thing as a random positive number. If you don't define the distribution, then it is meaningless to talk about a random number.
And you can't have a uniform random number on the interval (0,inf].
You CAN define a uniform random number on A BOUNDED SET. So, the interval[0,1]. But if you want to constrain the sum to be constant, then be careful. This question gets asked over and over again, and people answer it thinking you can solve it trivially. They generate a vector of numbers, and then scale them so the sum is the desired value. WRONG. This generates a distribution that is not in fact uniform.
So use a tool like randfixedsum , as found on the file exchange, or my own randFixedLinearCombination , also on the file exchange.
The latter tool is more capable for some problems, but for long vectors that sum to a constant, it will be inefficient. It probably won't work well in more than about 6 dimensions. But randfixedsum is fine beyond that point.
So to generate a set of 10 numbers that sum to 4, where each element in the vector is in the interval [.2, .6], is as simple as:
S = randfixedsum(10,1,4,.2,.6)
S =
0.4354
0.5535
0.2221
0.3235
0.4106
0.5368
0.3963
0.2636
0.4705
0.3877
sum(S)
ans =
4.0000
Again, DON'T use a rescaling scheme. Randfixedsum is perfect for the problem.