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 two consecutive (in order of the array) points but can't figure out how can I calculate the distance of each point with all other points. Every point will have 9 distances (with 9 other points), thus 10 points have a total of 45 distances (half of 90). So far I have found 9 distances only. Any idea how can get all the distances efficiently using python?
import numpy as np
import scipy as sp
rij_mat = np.zeros((9,1),dtype=np.float32) """created a 9x1 matrix for storing 9 distances for 10 points"""
npoints = 10
x = sp.randn(npoints,3)
print "here are the 3-d points..."
print x
for i in xrange(npoints-1):
rij_mat[i] = np.linalg.norm(x[i+1]-x[i])
print "the distances are..."
print rij_mat
My output right now is something like this:
here are the 3-d points...
[[-0.89513316 0.05061497 -1.19045606]
[ 0.31999847 -0.68013916 -0.14576028]
[ 0.85442751 -0.64139512 1.70403995]
[ 0.55855264 0.56652717 -0.17086825]
[-1.22435021 0.25683649 0.85128921]
[ 0.80310031 0.82236372 -0.40015387]
[-1.34356018 1.034942 0.00878305]
[-0.65347726 1.1697195 -0.45206805]
[ 0.65714623 -1.07237429 -0.75204526]
[ 1.17204207 0.89878048 -0.54657068]]
the distances are...
[[ 1.7612313 ]
[ 1.92584431]
[ 2.24986649]
[ 2.07833028]
[ 2.44877243]
[ 2.19557977]
[ 0.84069204]
[ 2.61432695]
[ 2.04763007]]
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.