Skip to content

Instantly share code, notes, and snippets.

@mgaitan
Created September 6, 2013 15:10
Show Gist options
  • Save mgaitan/6465190 to your computer and use it in GitHub Desktop.
Save mgaitan/6465190 to your computer and use it in GitHub Desktop.
Computes the distance between m points using Euclidean distance (2-norm) as the distance metric between the points. The points are arranged as m n-dimensional row vectors in the matrix X.
import numpy as np
def distance(X):
"""
Computes the distance between m points using Euclidean distance (2-norm)
as the distance metric between the points.
The points are arranged as m n-dimensional row vectors in the matrix X.
"""
# agregamos una dimension. Ahora X.shape == (m, 1, n)
# Por ejemplo np.all(X[0] == X_dim_plus[0, 0])
X_dim_plus = X[:, np.newaxis, :]
# elevamos los catetos de todos los puntos. genera una matriz de (m,m,n)
dist = (X_dim_plus - X)**2
# aplanamos la matriz sumando la última dimension. Ahora será (m,m)
dist = np.sum(dist, axis=-1)
# y por ultimo calculamos su raiz cuadrada.
return np.sqrt(dist)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment