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


hi build distance matrix size 10 x 10 , have generated list of values 45 real numbers fill in 10 x 10 matrices. distance matrix known symmetric matrix mirror other side of matrix. current situation have 45 values know how create distance matrix filled in 0 in diagonal part of matrix , create mirror matrix in order form complete distant matrix.

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.

assuming want create distance matrices of arbitrary size:

import math  def distance_matrix(pattern):     # side length, solve n len(pattern) = n*(n + 1)/2 (triangular number formula)     side_length = (int(math.sqrt(1 + 8 * len(pattern))) - 1) / 2 + 1     assert (side_length * (side_length - 1)) // 2 == len(pattern), "pattern length must triangular number."      # create grid     grid = [[0] * side_length in range(side_length)]      # fill in grid     position = 0     in range(0, side_length - 1):         j in range(0, side_length - 1 - i):             element = pattern[position]; position += 1             grid[i][i + j + 1] = element # fill in upper triangle             grid[i + j + 1][i] = element # fill in lower triangle      return grid  def matrix_to_string(matrix): return "\n".join("\t".join(str(x) x in row) row in distance_matrix([1, 2, 4, 3, 5, 6]))  if __name__ == "__main__":     print(matrix_to_string(distance_matrix([1, 2, 4, 3, 5, 6]))) 

Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -