How to generate a random matrix in C++?
16,802
You can accomplish this with STL's random_shuffle:
#include <vector>
#include <algorithm>
// Function that generates random array elements
int random_element();
const int n = 10; // Size of the array
const int k = 4; // Number of random (non-zero) elements in the array
int a[n]; // The array, filled with zeros
int main()
{
for (size_t i = 0; i < k; ++i)
a[i] = random_element();
std::random_shuffle(a, a + n);
// Now 'a' contains k random elements and (n-k) zeros, in a random order
}
Comments
-
xunzhang almost 2 years
I want to generate a matrix with fixed sparsity and random indexes and value.
In order to simplify the problem, take array for example: generate a arr[10] with just 3 location with non-zero value. If I just random these 3 indexes one-by-one, the efficiency of the algorithm is bad because of the repetition.
More difficult, I also want to generate a random matrix with rank k because null cols and rows may cause a bug with my code...How to make it this time?
Thanks!
-
Jonathan Leffler over 11 yearsWhat is the benefit of using the
r
array over initializing K elements to a random value, N-K elements to zero, and then shuffling the array? -
Gene over 11 yearsIf you have to initialize many times, you can keep r. You don't have to re-initialize it (first loop). All subsequent insertions of K elements need only K steps. The shuffle will require N. If you only have one initialization to do, the shuffle is better.
-
Admin about 7 yearsAlso, you can try with any size for the matrix.
-
Cecilia about 7 yearsIt looks like your code puts a random number in every row and column. The original question wants to put a small number of non-zero random values into a matrix. It's great that you're learning about programming, but this is not an answer to the original question.
-
einpoklum over 6 yearsWhy bother shuffling?
-
einpoklum over 6 yearsDon't use rand(), it is considered harmful.