Fitting a 2D Gaussian to 2D Data Matlab

2019-09-06 12:01发布

问题:

I have a vector of x and y coordinates drawn from two separate unknown Gaussian distributions. I would like to fit these points to a three dimensional Gauss function and evaluate this function at any x and y.

So far the only manner I've found of doing this is using a Gaussian Mixture model with a maximum of 1 component (see code below) and going into the handle of ezcontour to take the X, Y, and Z data out.

The problems with this method is firstly that its a very ugly roundabout manner of getting this done and secondly the ezcontour command only gives me a grid of 60x60 but I need a much higher resolution.

Does anyone know a more elegant and useful method that will allow me to find the underlying Gauss function and extract its value at any x and y?

Code:

GaussDistribution = fitgmdist([varX varY],1); %Not exactly the intention of fitgmdist, but it gets the job done.
h = ezcontour(@(x,y)pdf(GaussDistributions,[x y]),[-500 -400], [-40 40]);

回答1:

Gaussian Distribution in general form is like this:

I am not allowed to upload picture but the Formula of gaussian is:

1/((2*pi)^(D/2)*sqrt(det(Sigma)))*exp(-1/2*(x-Mu)*Sigma^-1*(x-Mu)');

where D is the data dimension (for you is 2); Sigma is covariance matrix; and Mu is mean of each data vector.

here is an example. In this example a guassian is fitted into two vectors of randomly generated samples from normal distributions with parameters N1(4,7) and N2(-2,4):

Data = [random('norm',4,7,30,1),random('norm',-2,4,30,1)];
X = -25:.2:25;
Y = -25:.2:25;

D = length(Data(1,:));
Mu = mean(Data);
Sigma = cov(Data);
P_Gaussian = zeros(length(X),length(Y));
for i=1:length(X)
   for j=1:length(Y)
       x = [X(i),Y(j)];
       P_Gaussian(i,j) = 1/((2*pi)^(D/2)*sqrt(det(Sigma)))...
                    *exp(-1/2*(x-Mu)*Sigma^-1*(x-Mu)');
   end
end

mesh(P_Gaussian)

run the code in matlab. For the sake of clarity I wrote the code like this it can be written more more efficient from programming point of view.