Search code examples
matlabmatrixdistancemahalanobis

matlab Pdist2 with mahalanobis metric


How can i use pdist2 with 'mahalanobis' metric? I write this code :

u=[1 2 3; 4 5 6; 7 8 9];
n=[1 2 5;2 5 7;5 7 9];
covu=nancov(u);

Z=pdist2(u,u,'mahalanobis',covu);

But i get this error:

??? Error using ==> pdist2 at 298
The covariance matrix for the Mahalanobis metric must be symmetric and positive definite.

Error in ==> Untitled at 5
Z=pdist2(u,u,'mahalanobis',covu); 

although variable 'covuu' is symmetric matrix and also positive. this is covu: covu =

 9     9     9
 9     9     9
 9     9     9

How can i calculate pdist2 with "mahalabobis" metric?


Solution

  • The matrix must be positive definite which is not the same as having positive entries. In the case of a symmetric matrix this means that all eigenvalues must be positive. But in your case the matrix has only rank 1. If you compute the eigenvalues you see exactly that, two eigenvalues are zero:

    eig(covu)
    
    ans =
    
       -0.0000
        0.0000
       27.0000