function dists = mahalonobis(data, exemplars)
% mahalonobis(data,exemplars)
% compute the mahalonobis distance of each
% point in data from the mean of the exemplars
% each column in data (and exemplars) is one
% coordinate in the space.
[m,n] = size(data);
mn = mean(exemplars);

if length(mn) ~= n
   error('Mahalonobis: data and exemplars must have the same width');
end

for k=1:n
   data(:,k) = data(:,k) - mn(k);
end

mat = inv(cov(exemplars));

dists = zeros(m,1);
for k=1:n
   for j=k:n
      if j==k
         factor = 1;
      else
         factor = 2;
      end
      dists = dists + factor*mat(k,j).*data(:,k).*data(:,j);
   end
end
dists = sqrt(dists);
