D = mahal(obj,X)
D = mahal(obj,X) computes the Mahalanobis distance (in squared units) of each observation in X to the mean of each of the k components of the Gaussian mixture distribution defined by obj. obj is an object created by gmdistribution or fit. X is an n-by-d matrix, where n is the number of observations and d is the dimension of the data. D is n-by-k, with D(I,J) the distance of observation I from the mean of component J.
Generate data from a mixture of two bivariate Gaussian distributions using the mvnrnd function:
MU1 = [1 2]; SIGMA1 = [2 0; 0 .5]; MU2 = [-3 -5]; SIGMA2 = [1 0; 0 1]; X = [mvnrnd(MU1,SIGMA1,1000);mvnrnd(MU2,SIGMA2,1000)]; scatter(X(:,1),X(:,2),10,'.') hold on
Fit a two-component Gaussian mixture model:
obj = gmdistribution.fit(X,2); h = ezcontour(@(x,y)pdf(obj,[x y]),[-8 6],[-8 6]);
Compute the Mahalanobis distance of each point in X to the mean of each component of obj:
D = mahal(obj,X); delete(h) scatter(X(:,1),X(:,2),10,D(:,1),'.') hb = colorbar; ylabel(hb,'Mahalanobis Distance to Component 1')