Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to create a complete distance matrix from a row of values?

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.

like image 679
Allyson Avatar asked Oct 18 '25 12:10

Allyson


1 Answers

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.]])
like image 165
user2357112 supports Monica Avatar answered Oct 21 '25 02:10

user2357112 supports Monica