Random positive numbers with constant sum
9 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Joseph Lee
am 8 Nov. 2017
Bearbeitet: Joseph Lee
am 9 Nov. 2017
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
0 Kommentare
Akzeptierte Antwort
John D'Errico
am 8 Nov. 2017
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.
4 Kommentare
John D'Errico
am 8 Nov. 2017
Be serious. Surely it cannot be difficult to transpose the result?
R = randfixedsum(10,1300,4,.2,.6)';
size(R)
ans =
1300 10
sum(R(1,:))
ans =
4
Weitere Antworten (1)
Torsten
am 8 Nov. 2017
https://de.mathworks.com/matlabcentral/fileexchange/9700-random-vectors-with-fixed-sum
Best wishes
Torsten.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Random Number Generation finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!