Question: 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](http:///https://en.wikipedia.org/wiki/Symmetric_matrix) 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...

Answer: 
You could xor a random matrix with its transpose:

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

```
```
import numpy as np

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

```

`-1` in [`tril`](https://numpy.org/doc/stable/reference/generated/numpy.tril.html) sets all elements above the diagonal just below the main diagonal to zero, so it effectively sets the main diagonal to zero.