Fitting a 2D Gaussian to 2D Data Matlab

萝らか妹 提交于 2020-01-16 12:28:41

问题


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.



来源:https://stackoverflow.com/questions/28343056/fitting-a-2d-gaussian-to-2d-data-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!