#!/usr/bin/perl use warnings; use strict; use PDL; # ================================ # mahalanobis: # # $distance = mahalanobis( $x, $y, $cov ) # # computes the mahalanobis distance from a point # $x to another point $y (from the same # distribution) or from a point $x to # the centre of a group of values $y # # ================================ sub mahalanobis { my ( $x, $y, $cov, $diff, $dist ); if ( @_ < 3 ) { ( $x, $y ) = @_; $cov = covariance( $y ); } else { ( $x, $y, $cov ) = @_; } if ( $y->getdim(1) > 1 ) { $diff = $x - average( $y->xchg(0,1) ); } else { $diff = $x - $y; } my @dist = list( $diff x inv( $cov ) x transpose( $diff ) ); return $dist[0]; }