I want to create a symmetric matrix with random numbers in python.
Example for symmetrical matrix:
| A | B | C | D | |
|---|---|---|---|---|
| A | 0 | 1 | 2 | 3 |
| B | 1 | 0 | 5 | 4 |
| C | 2 | 5 | 0 | 6 |
| D | 3 | 4 | 6 | 0 |
The numbers except for the 0’s are random.
Is there an efficient way to do this? I know how to do it manually, but depending on the size of the matrix it can be much work.
Thanks!
>Solution :
import numpy as np
n = 6
a = np.random.randint(0, 100, (n, n))
m = np.tril(a, -1) + np.tril(a, -1).T
m
# array([[ 0, 84, 90, 38, 74, 95],
# [84, 0, 28, 55, 83, 52],
# [90, 28, 0, 82, 42, 46],
# [38, 55, 82, 0, 1, 70],
# [74, 83, 42, 1, 0, 64],
# [95, 52, 46, 70, 64, 0]])