SB26
SB26

Reputation: 225

Mahalanobis distance in Matlab

I am trying to find the Mahalanobis distance of some points from the origin.The MATLAB command for that is mahal(Y,X)

But if I use this I get NaN as the matrix X =0 as the distance needs to be found from the origin.Can someone please help me with this.How should it be done

Upvotes: 2

Views: 4938

Answers (1)

ely
ely

Reputation: 77434

I think you are a bit confused about what mahal() is doing. First, computation of the Mahalanobis distance requires a population of points, from which the covariance will be calculated.

In the Matlab docs for this function it makes it clear that the distance being computed is:

d(I) = (Y(I,:)-mu)*inv(SIGMA)*(Y(I,:)-mu)'

where mu is the population average of X and SIGMA is the population covariance matrix of X. Since your population consists of a single point (the origin), it has no covariance, and so the SIGMA matrix is not invertible, hence the error where you get NaN/Inf values in the distances.

If you know the covariance structure that you want to use for the Mahalanobis distance, then you can just use the formula above to compute it for yourself. Let's say that the covariance you care about is stored in a matrix S. You want the distance w.r.t. the origin, so you don't need to subtract anything from the values in Y, all you need to compute is:

for ii = 1:size(Y,1)
    d(ii) = Y(ii,:)*inv(S)*Y(ii,:)'; % Where Y(ii,:) is assumed to be a row vector.'
end

Upvotes: 3

Related Questions