Home > Blockchain >  Generate a random symmetric binary matrix in Python
Generate a random symmetric binary matrix in Python

Time:11-26

I've looked for several question on SO but couldn't find this or figure it out how to do it. I want to generate a random symmetric binary matrix (n x n), from a given n.

Examples (n=3):

    0 0 1         0 0 1 
    0 0 1   or    0 0 0
    1 1 0         1 0 0
              

I also need the main diagonal to be zero. I know how to do it later, but in case one already want to implement it in an optimal code...

CodePudding user response:

You could xor a random matrix with its transpose:

a = np.random.randint(0, 2, (n, n))
a ^= a.T

CodePudding user response:

import numpy as np

n = 3
a = np.tril(np.random.randint(0, 2, (n,n)), -1)
print(a   a.T)

-1 in tril sets all elements above the diagonal just below the main diagonal to zero, so it effectively sets the main diagonal to zero.

CodePudding user response:

You could generate a random array and fill one triangle with the 180° rotation of the array. Finally, fill the diagonal with 0.

N = 3
a = np.random.randint(2,size=(N,N))
a[np.tril_indices(N)] = np.rot90(a, k=2)[np.tril_indices_from(a)]
np.fill_diagonal(a, 0)

Alternatively, you can use a XOR that is faster (X^Y yields 1 if X is different from Y):

N = 3
a = np.random.randint(2,size=(N,N))
(a^np.rot90(a, k=2))
np.fill_diagonal(a, 0)

Example with N=3:

array([[0, 1, 1],
       [0, 0, 0],
       [1, 1, 0]])

Example with N=5:

array([[0, 1, 1, 1, 0],
       [1, 0, 1, 1, 0],
       [0, 1, 0, 1, 0],
       [0, 1, 1, 0, 1],
       [0, 1, 1, 1, 0]])
  • Related