Search code examples
matlabmixture-modelgmm

Gaussian mixture model - get the contour of given probability value : Matlab


I need to identify the 99% probability contour of a GMM fitted to data. Following this example, I'd like to be able to specify which contours to plot, and the x,y, of them.

mu1 = [1 2]; Sigma1 = [2 0; 0 0.5];
mu2 = [-3 -5]; Sigma2 = [1 0;0 1];
X = [mvnrnd(mu1,Sigma1,1000); mvnrnd(mu2,Sigma2,1000)];
GMModel = fitgmdist(X,2);
figure
y = [zeros(1000,1);ones(1000,1)];
h = gscatter(X(:,1),X(:,2),y);
hold on
gmPDF = @(x,y) arrayfun(@(x0,y0) pdf(GMModel,[x0 y0]),x,y);
g = gca;
fcontour(gmPDF,[g.XLim g.YLim])
title('{\bf Scatter Plot and Fitted Gaussian Mixture Contours}')
legend(h,'Model 0','Model1')
hold off

So, in the following figure, I'd like to to be able to plot the 99% in dashed black line "k". Any idea how to accomplish this?

enter image description here


Solution

  • You can display and get the coordinates of the given contour line specifying the LevelList property of fcontour, and then reading the ContourMatrix property of the contour handle:

    % Random function, insert here yours
    f = @(x,y) arrayfun(@(x0,y0) x0.^2 + y0.^2 - 0.1,x,y);
    
    % The function value you want to get the contour for
    lvl = 0.99;
    
    % Plot the contour line
    cHandle = fcontour(f, '--k', 'LevelList', [lvl]);
    hold on
    
    % Get the coordinates
    lvlX = cHandle.ContourMatrix(1, 2:end);
    lvlY = cHandle.ContourMatrix(2, 2:end);
    
    % For a check:
    plot(lvlX, lvlY, '--r')