Skip to content

Instantly share code, notes, and snippets.

@dboyliao
Last active May 3, 2020 16:25
Show Gist options
  • Save dboyliao/bfb929f1c8e4028747d4448453433a29 to your computer and use it in GitHub Desktop.
Save dboyliao/bfb929f1c8e4028747d4448453433a29 to your computer and use it in GitHub Desktop.
import numpy as np
def distance_vec(X):
# (x - y)^2 = x^2 + y^2 - 2xy
prod = -2 * X.dot(X.T)
sq = (X ** 2).sum(axis=-1)
return sq + sq[:, None] + prod
def distance_vec_v2(X):
# Thanks to Peter Cheng
diff = X[:, None, :] - X[None, :, :]
return (diff ** 2).sum(axis=-1) ** 0.5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment