Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Symmetric Matrix Python

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading