I have a set of 3D points, where I need to find the distances of every point with all other points. So far I came up with the code as below to calculate the distances between tw
How about two loops instead of one?
distances = []
for i in xrange(npoints-1):
for j in range(i+1, npoints):
distances.append(np.linalg.norm(x[i]-x[j])
For each of your npoints
points, there are exactly npoints - 1
other points to compare with, for distance. And, the distance between x[m]
and x[n]
is the same as the distance between x[n]
and x[m]
, so that cuts the total number of distances in half. The itertools
package has a nice way to handle this:
import numpy as np
import scipy as sp
import itertools as its
npoints = 10
nCombos = (npoints * (npoints - 1))/2
x = sp.randn(npoints,3)
rij_mat = np.zeros(nCombos)
ii = 0
for i1, i2 in its.combinations(range(npoints), 2):
rij_mat[ii] = np.linalg.norm(x[i1]-x[i2])
ii += 1
print "the distances are..."
print rij_mat
If you're a really careful person, you might check at the end that ii == nCombos
.
Since you called your output matrix rij_mat
, maybe you intended it to be a 2-dimensional matrix? Then you'd want something like:
import numpy as np
import scipy as sp
import itertools as its
npoints = 10
x = sp.randn(npoints,3)
rij_mat = np.zeros((npoints, npoints))
for i1, i2 in its.combinations(range(npoints), 2):
rij_mat[i2, i1] = rij_mat[i1, i2] = np.linalg.norm(x[i1]-x[i2])
print "the distances are..."
print rij_mat