Hi I would like to build a distance matrix with size 10 x 10 and I have generated a list of values which is 45 real numbers to fill in the 10 x 10 matrices. Distance matrix also known as symmetric matrix it is a mirror to the other side of the matrix. My current situation is that I have the 45 values I would like to know how to create distance matrix with filled in 0 in the diagonal part of matrix and create mirror matrix in order to form a complete distant matrix.
For example,
1, 2, 4, 3, 5, 6
Output:
0, 1, 2, 4
1, 0, 3, 5
2, 3, 0, 6
4, 5, 6, 0
Thanks.
If you're using NumPy, this would be a perfect job for numpy.triu_indices
, which returns a pair of index arrays suitable for selecting the upper triangle of a matrix. The first argument is the side length of the matrix, and the second argument is which diagonal to start from:
In [1]: import numpy
In [2]: x = numpy.zeros([4, 4]) # 4x4 array of zeros
In [3]: x[numpy.triu_indices(4, 1)] = [1, 2, 4, 3, 5, 6]
In [4]: x
Out[4]:
array([[ 0., 1., 2., 4.],
[ 0., 0., 3., 5.],
[ 0., 0., 0., 6.],
[ 0., 0., 0., 0.]])
In [5]: x += x.T
In [6]: x
Out[6]:
array([[ 0., 1., 2., 4.],
[ 1., 0., 3., 5.],
[ 2., 3., 0., 6.],
[ 4., 5., 6., 0.]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With