필터 지우기
필터 지우기

Random positive numbers with constant sum

조회 수: 9 (최근 30일)
Joseph Lee
Joseph Lee 2017년 11월 8일
편집: Joseph Lee 2017년 11월 9일
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

채택된 답변

John D'Errico
John D'Errico 2017년 11월 8일
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
John D'Errico
John D'Errico 2017년 11월 8일
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
Joseph Lee
Joseph Lee 2017년 11월 9일
편집: Joseph Lee 2017년 11월 9일
my mistake, it was not related to that, just that the formula i input for the sum was wrong which caused that error. Thanks a lot

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Torsten
Torsten 2017년 11월 8일
https://de.mathworks.com/matlabcentral/fileexchange/9700-random-vectors-with-fixed-sum
Best wishes
Torsten.

카테고리

Help CenterFile Exchange에서 Random Number Generation에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by