Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

maha

Fast computation of squared mahalanobis distance between all rows of X and the vector mu with respect to sigma.


Description

Fast computation of squared mahalanobis distance between all rows of X and the vector mu with respect to sigma.

Usage

maha(X, mu, sigma, ncores = 1, isChol = FALSE)

Arguments

X

matrix n by d where each row is a d dimensional random vector. Alternatively X can be a d-dimensional vector.

mu

vector of length d, representing the central position.

sigma

covariance matrix (d x d). Alternatively is can be the cholesky decomposition of the covariance. In that case isChol should be set to TRUE.

ncores

Number of cores used. The parallelization will take place only if OpenMP is supported.

isChol

boolean set to true is sigma is the cholesky decomposition of the covariance matrix.

Value

a vector of length n where the i-the entry contains the square mahalanobis distance i-th random vector.

Author(s)

Matteo Fasiolo <matteo.fasiolo@gmail.com>

Examples

N <- 100
d <- 5
mu <- 1:d
X <- t(t(matrix(rnorm(N*d), N, d)) + mu)
tmp <- matrix(rnorm(d^2), d, d)
mcov <- tcrossprod(tmp, tmp)
myChol <- chol(mcov)

rbind(head(maha(X, mu, mcov), 10),
      head(maha(X, mu, myChol, isChol = TRUE), 10),
      head(mahalanobis(X, mu, mcov), 10))

## Not run: 
# Performance comparison: microbenchmark does not work on all
# platforms, hence we need to check whether it is installed
if( "microbenchmark" %in% rownames(installed.packages()) ){
library(microbenchmark)

a <- cbind(
  maha(X, mu, mcov),
  maha(X, mu, myChol, isChol = TRUE),
  mahalanobis(X, mu, mcov))
  
# Same output as mahalanobis
a[ , 1] / a[, 3]
a[ , 2] / a[, 3]

microbenchmark(maha(X, mu, mcov),
               maha(X, mu, myChol, isChol = TRUE),
               mahalanobis(X, mu, mcov))
}

## End(Not run)

mvnfast

Fast Multivariate Normal and Student's t Methods

v0.2.5.1
GPL (>= 2.0)
Authors
Matteo Fasiolo [aut, cre], Thijs van den Berg [ctb]
Initial release
2018-01-31

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.