\Header{mahalanobis}{Mahalanobis Distance}
\keyword{multivariate}{mahalanobis}
\begin{Description}\relax
Returns the Mahalanobis distance of all rows in \code{x} and the
vector \eqn{\mu=}{}\code{center} with respect to
\eqn{\Sigma=}{}\code{cov}.
This is (for vector \code{x}) defined as
\deqn{
D^2 = (x - \mu)' \Sigma^{-1} (x - \mu)
}{}\end{Description}
\begin{Usage}
\begin{verbatim}
mahalanobis(x, center, cov, inverted=FALSE)
\end{verbatim}
\end{Usage}
\begin{Arguments}
\begin{ldescription}
\item[\code{x}] vector or matrix of data with, say, \eqn{p}{} columns.
\item[\code{center}] mean vector of the distribution or second data vector of
length \eqn{p}{}.
\item[\code{cov}] covariance matrix (\eqn{p \times p}{p x p}) of the distribution.
\item[\code{inverted}] logical.  If \code{TRUE}, \code{cov} is supposed to
contain the \emph{inverse} of the covariance matrix.
\end{ldescription}
\end{Arguments}
\begin{Author}\relax
Friedrich Leisch\end{Author}
\begin{SeeAlso}\relax
\code{\Link{cov}}, \code{\Link{var}}\end{SeeAlso}
\begin{Examples}
\begin{ExampleCode}
ma <- cbind(1:6, 1:3)
(S <-  var(ma))
mahalanobis(c(0,0), 1:2, S)

x <- matrix(rnorm(100*3), ncol = 3)
stopifnot(mahalanobis(x, 0, diag(ncol(x))) == apply(x*x, 1, sum))
        ##- Here, D^2 = usual Euclidean distances
Sx <- cov(x)
D2 <- mahalanobis(x, apply(x, 2, mean), Sx)
plot(density(D2, bw=.5), main="Mahalanobis distances, n=100, p=3"); rug(D2)
qqplot(qchisq(ppoints(100), df=3), D2,
       main = expression("Q-Q plot of Mahalanobis" * ~D^2 *
                         " vs. quantiles of" * ~ chi[3]^2))
abline(0, 1, col = 'gray')
\end{ExampleCode}
\end{Examples}

