フィルターのクリア

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 Center および File ExchangeRandom Number Generation についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by