I need your help and I will be very happy if you can help me. I need to generate a matrice like M=. I have another two arrays which show the starting and ending points of random value interval S=[2 3] and E=[4 7]. I need to generate M matrix which have two rows. In the first row starting from 2 coloum to the 4th one I need to assign random values whose sum equal to 1. The same thing for the second row as well. What I want to do is :
M=[0 0.1 0.2 0.7 0 0 0 0 0 0]
[0 0 0.1 0.2 0.3 0.3 0.1 0 0 0] The values will be sum random values between 0 and 1 whose sum is equal to 1.
divide the number of numbers you need into 1. if you need 10 numbers, then set up your <random> interval to be 0 to 0.1. one of the values, randomly chose, hold it back. Subtract the sum of the others from 1, and set the last value to make up the difference.
for your own sanity, so you don't get 0.42e-267 , you may want to set that interval to 0.0001 to 0.1 or something like that.
if you want to allow negative numbers, its an entirely different game... but the same ideas.
floating point values and equality.. you may also want to allow it to be 'almost 1' sum, or work in integer space and apply the decimal after.
mt19937 gen( time( 0 ) );
uniform_real_distribution<double> dist( 0.0, 1.0 );
valarray<double> getValues( int N )
for ( double &e : V ) e = dist( gen );
return V / V.sum();
cout << "How many numbers? "; cin >> N;
valarray<double> V = getValues( N );
for ( double e : V ) cout << e << ' ';
How many numbers? 4
0.283817 0.347848 0.193431 0.174903