Quickly calculates and returns the Euclidean distances between m vectors in one set and n vectors in another. Each set of vectors is given as the columns of a matrix.

L2_distance(a, b, df = 0)



A d by m numeric matrix giving the first set of m vectors of dimension d as the columns of a.


A d by n numeric matrix giving the second set of n vectors of dimension d as the columns of b.


Indicator whether to force the diagonals of the returned matrix to be zero (df = 1) or not (the default df = 0).


An m by n matrix containing the Euclidean distances between the column vectors of the matrix a and the column vectors of the matrix b.


This fully vectorized (VERY FAST!) function computes the Euclidean distance between two vectors by:

||A-B|| = sqrt ( ||A||^2 + ||B||^2 - 2*A.B )

Originally written as L2_distance.m for Matlab by Roland Bunschoten of the University of Amsterdam, Netherlands.

See also


A <- matrix(rnorm(400), nrow = 10) B <- matrix(rnorm(800), nrow = 10) L2_distance(A[,1, drop = FALSE], B[,1, drop = FALSE])
#> [,1] #> [1,] 6.139374
d_AB <- L2_distance(A,B) d_BB <- L2_distance(B,B, df = 1) # force diagonal to be zero