% mahal_dist_demo.m
% Compare the Euclidean Distance and Mahalanobis Distance on data with
% correlation.
% David Pan, UAH

close all
m = [0, 0]
C =[8 4; 4 8]
eig(C)
Q = mvnrnd(m,C,1000);
figure;
scatter(Q(:,1),Q(:,2))
grid
axis equal
axis square
smean = mean(Q)  % Sample mean
scov = cov(Q)    % Sample covariance matrix

hold on;
x = linspace(-12,12);
y = linspace(-12,12);
[X,Y] = meshgrid(x,y);
% Euclidean Distances
D_Euc = sqrt((X - smean(1)).^2 + (Y - smean(2)).^2);
contour(X,Y,D_Euc,'ShowText', 'on')


% Mahalanobis Distance from the sample mean vector
D_Mah = zeros(100, 100);
for i = 1: 100
    for j = 1: 100
        D_Mah(i,j) = pdist2([X(i,j),Y(i,j)], smean, 'mah', scov);
    end
end

figure
scatter(Q(:,1),Q(:,2))
grid
axis equal
axis square
hold on;

contour(X,Y,D_Mah,'ShowText', 'on')


