www.gusucode.com > stats 源码程序 matlab案例代码 > stats/CompareMahalanobisAndSquaredEuclideanDistancesExample.m

    %% Compare Mahalanobis and Squared Euclidean Distances
%%
% Generate correlated bivariate data.

% Copyright 2015 The MathWorks, Inc.

X = mvnrnd([0;0],[1 .9;.9 1],100);
%%
% Input observations.
Y = [1 1;1 -1;-1 1;-1 -1];
%%
% Compute the Mahalanobis distance of observations in |Y| from the
% reference sample in |X| .
d1 = mahal(Y,X)
%%
% Compute their squared Euclidean distances from the mean of |X| .
d2 = sum((Y-repmat(mean(X),4,1)).^2, 2)
%%
% Plot the observations with |Y| values colored according to the
% Mahalanobis distance.
scatter(X(:,1),X(:,2))
hold on
scatter(Y(:,1),Y(:,2),100,d1,'*','LineWidth',2)
hb = colorbar;
ylabel(hb,'Mahalanobis Distance')
legend('X','Y','Location','NW')
%%
% The observations in |Y| with equal coordinate values are much closer to
% |X| in Mahalanobis distance than observations with opposite coordinate
% values, even though all observations are approximately equidistant from
% the mean of |X| in Euclidean distance. The Mahalanobis distance, by
% considering the covariance of the data and the scales of the different
% variables, is useful for detecting outliers in such cases.