R: Mahalanobis distance

Mahalanobis {fastmatrix} | R Documentation

## Mahalanobis distance

### Description

Returns the squared Mahalanobis distance of all rows in `x` and the vector \bold{μ} = `center` with respect to \bold{Σ} = `cov`. This is (for vector `x`) defined as

D^2 = (\bold{x} - \bold{μ})^T \bold{Σ}^{-1} (\bold{x} - \bold{μ})

### Usage

    Mahalanobis(x, center, cov, inverted = FALSE)

### Arguments

`x` | vector or matrix of data. As usual, rows are observations and columns are variables.
`center` | mean vector of the distribution.
`cov` | covariance matrix (p x p) of the distribution, must be positive definite.
`inverted` | logical. If `TRUE`, `cov` is supposed to contain the inverse of the covariance matrix.

### Details

Unlike function `mahalanobis`, the covariance matrix is factorized using the Cholesky decomposition, which allows to assess if `cov` is positive definite. Unsuccessful results from the underlying LAPACK code will result in an error message.

### See Also

`cov`, `mahalanobis`

### Examples

    x <- cbind(1:6, 1:3)
    xbar <- colMeans(x)
    S <- matrix(c(1,4,4,1), ncol = 2) # is negative definite
    D2 <- mahalanobis(x, center = xbar, S)
    all(D2 >= 0) # several distances are negative

    ## next command produces the following error:
    ## Covariance matrix is possibly not positive-definite
    ## Not run: D2 <- Mahalanobis(x, center = xbar, S)

[Package fastmatrix version 0.4-1 Index]