1

For each point in 3D, I want to get its distance from all points across the same dimension. Something along these lines but vectorized:

points = np.array([[1, 2], [-2, 4], [6, -1]])

dims, num_points = points.shape
dist = np.zeros((dims, num_points, num_points))
for d in range(dims):
    for i in range(num_points):
        for j in range(num_points):
            dist[d][i][j] = points[d][i] - points[d][j]
...
>>> dist
array([[[ 0., -1.],
        [ 1.,  0.]],

       [[ 0., -6.],
        [ 6.,  0.]],

       [[ 0.,  7.],
        [-7.,  0.]]])


Roman
  • 129
  • 1
  • 9
  • 3
    Use `points[..., None] - points[:, None]`, dupe of several outer broadcasting questions – user3483203 Sep 06 '19 at 00:47
  • 1
    Same idea as [this](https://stackoverflow.com/questions/42378936/numpy-elementwise-outer-product), but with subtraction. – user3483203 Sep 06 '19 at 00:48
  • This is not a distance, but just the difference vector. If that is what you want, do as user3483203 suggests. If you actually want to compute distances, you could use [`scipy.spatial.distance.pdist`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist.html). – jdehesa Sep 06 '19 at 12:55
  • @jdehesa no this is exactly what I want, matches my for loop code. – Roman Sep 06 '19 at 17:00

0 Answers0