Matrix Generation by assigning random values to the given index

Hello everyone ,

I need your help and I will be very happy if you can help me. I need to generate a matrice like M=[2][10]. 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.

How can I do that ? Thank you so much in advance



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.
Last edited on
For each row:

- generate the required number of values in the interval [0,1) using functions in <random> e.g.
https://www.cplusplus.com/reference/random/uniform_real_distribution/

- calculate the sum of these values

- divide all the values by their sum (they will then add up to 1)

- assign to the appropriate elements of your matrix
Last edited on
that is much better... ^^^
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <valarray>
#include <random>
#include <ctime>
using namespace std;

mt19937 gen( time( 0 ) );
uniform_real_distribution<double> dist( 0.0, 1.0 );

valarray<double> getValues( int N )
{
   valarray<double> V(N);
   for ( double &e : V ) e = dist( gen );
   return V / V.sum();
}

int main()
{
   int N;
   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  
Last edited on
Thank you so much @lastchance and @jonnin. Your explanations and exampla helped me .
Topic archived. No new replies allowed.