最近拟合高斯分布的期望和方差,我写了个使用最小二乘法拟合的函数,经过测试效果还不错。现在公布源码吧,希望能给需要的朋友一些参考。
function[u,sigma] = GaussFitting(x,y)
%====================================================================
% date: 2011/03/26
% created by hfeng
%参数x,y分别为高斯函数观察值x,y
%高斯函数参数拟合
%高斯函数 y = (1/(sqrt(2*pi)*sigma))exp(-(x-u)^2/(2*sigma^2)) (y>=0)
%剔除数据中y = 0 的情况,ln(y)定义域y>0.
%ln(y) =
%(-1/(2*sigma^2))*x^2+(u/(2*sigma^2))*x+ln(1/(sqrt(2*pi)*sigma))-u^2/(2*sigma^2)
%令 a = -1/(2*sigma^2) , b = u/(2*sigma^2) ,
% c = ln(1/(sqrt(2*pi)*sigma))-u^2/(2*sigma^2)
%高斯函数转化为 ln(y) = a*x^2 + b*x +c
%经过最小二乘法求出 a,b,c值
%进而求得 u,sigma值
%====================================================================
k = find(y==0);
y(k) = [];
x(k) = [];
lny = log(y);
param = polyfit(x,y,2);
a = param(1);
b = param(2);
c = param(3);
u = -b/(2*a);
sigma = sqrt(-1/(2*a));