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
}
Share:
16,802
xunzhang
Author by

xunzhang

OCD

Updated on June 04, 2022

Comments

  • xunzhang
    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
    Jonathan Leffler over 11 years
    What 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
    Gene over 11 years
    If 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
    Admin about 7 years
    Also, you can try with any size for the matrix.
  • Cecilia
    Cecilia about 7 years
    It 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
    einpoklum over 6 years
    Why bother shuffling?
  • einpoklum
    einpoklum over 6 years
    Don't use rand(), it is considered harmful.