List of coordinates to matrix of distances

3k views Asked by At

I've got a list of 8 coordinates stored as list of lists:

coordinates = [[47.2486, -1.54806],
               [43.5656, 1.47417],
               [48.3592, -4.57],
               [48.1439, 17.1097],
               [39.6275, 140.198],
               [30.0458, 31.2625],
               [38.9371, -77.0869],
               [33.9, 35.4823]]

With the following script, I seek to output a matrix of coordinates:

import numpy
from scipy.spatial.distance import pdist

coordinates_array = numpy.array(coordinates)
dist_array = pdist(coordinates_array)

dist_matrix = numpy.reshape(dist_array, newshape=(len(coordinates), len(coordinates)))

However, I get an ValueError: total size of new array must be unchanged. Why is that?

1

There are 1 answers

0
rth On BEST ANSWER

As explained in the scipy documentation, use scipy.spatial.distance.squareform to convert the condensed distance matrix returned by pdist to a square distance matrix,

from scipy.spatial.distance import squareform 

dist_matrix = squareform(dist_array)