# distmat: Distance Matrix

### Description

Computes the Euclidean distance between rows of two matrices.

### Usage

 ```1 2 3``` ```distmat(X, Y) pdist(X) pdist2(X, Y) ```

### Arguments

 `X` matrix of some size `m x k`; vector will be taken as row matrix. `Y` matrix of some size `n x k`; vector will be taken as row matrix.

### Details

Computes Euclidean distance between two vectors A and B as:

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

and vectorizes to rows of two matrices (or vectors).

`pdist2` is an alias for `distmat`, while `pdist(X)` is the same as `distmat(X, X)`.

### Value

matrix of size `m x n` if `x` is of size `m x k` and `y` is of size `n x k`.

### Note

If `a` is `m x r` and `b` is `n x r` then

`apply(outer(a,t(b),"-"),c(1,4),function(x)sqrt(sum(diag(x*x))))`

is the `m x n` matrix of distances between the `m` rows of `a` and `n` rows of `b`.

This can be modified as necessary, if one wants to apply distances other than the euclidean.

BUT: The code shown here is 10-100 times faster, utilizing the similarity between Euclidean distance and matrix operations.

### References

Copyright (c) 1999 Roland Bunschoten for a Matlab version on MatlabCentral under the name `distance.m`. Translated to R by Hans W Borchers.

`dist`

### Examples

 ```1 2 3 4 5 6 7 8``` ```A <- c(0.0, 0.0) B <- matrix(c( 0,0, 1,0, 0,1, 1,1), nrow=4, ncol = 2, byrow = TRUE) distmat(A, B) #=> 0 1 1 sqrt(2) X <- matrix(rep(0.5, 5), nrow=1, ncol=5) Y <- matrix(runif(50), nrow=10, ncol=5) distmat(X, Y) ```

Search within the pracma package
Search all R packages, documentation and source code

Questions? Problems? Suggestions? or email at ian@mutexlabs.com.

Please suggest features or report bugs with the GitHub issue tracker.

All documentation is copyright its authors; we didn't write any of that.