Learn R Programming

loon (version 1.4.1)

L2_distance: Euclidean distance between two vectors, or between column vectors of two matrices.

Description

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.

Usage

L2_distance(a, b, df = 0)

Value

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.

Arguments

a

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

b

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

df

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

Author

Roland Bunschoten (original), Adrian Waddell, Wayne Oldford

Details

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

Examples

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

Run the code above in your browser using DataLab