How to fit gaussian with Matlab with given height

时间秒杀一切 提交于 2019-12-25 04:53:09

问题


I am currently unable to have accurate gaussian fit. How can I fix the height? (see picture).

ft=fit(x,y,'gauss2') 
Co=coeffvalues(ft)
sigma=Co(3)/sqrt(2)  
mu = Co(2)
C=Co(1)

plot(X,C*exp(-(X - mu).^2 / (2*sigma^2))+min(y), '-r') 

回答1:


You can try lsqcurvefit to do single or multiple Gaussian fitting accurately.

x = lsqcurvefit(fun,x0,xdata,ydata)

fun is your Gaussian function, x0 holds the initial value of the Gaussian parameters (mu, sigma, height, etc). fun(x0) return the gaussian in vector/array form. When the routine returns, the fitted parameters are in x. You can customize the function fun to fit one Gaussian or multiple Gaussians to your data.

Matlab document of lsqcurvefit

In my case, I use the following routine to do multiple Gaussian fitting:

x0 = [1000;10.6;0.6;
     1100;12.8;0.7; %3 Gaussians
     300;10;2];     %each row is the height, mu, sigma of one Gaussian

options = optimset('TolFun',10e-6,'MaxFunEvals',150000);
%lb, ub are the similar matrix as x0 that define lower and upper bound of x.
[x, resnorm] = lsqcurvefit(@myfit, x0, xdata, ydata, lb, ub);

The myfit function that calculates superposition of multiple Gaussians:

function [ F ] = myfit(x, xdata)
    F = zeros(1,size(xdata,2));
    len = size(x,1);
    for i = 1:3:len
        F = F + x(i)*gauss(xdata, x(i+1), x(i+2));
    end
end

The Gaussian function:

function [ g ] = gauss(x, mu, sigma)
    g = exp(-0.5*((x-mu)/sigma).^2);
end


来源:https://stackoverflow.com/questions/20586006/how-to-fit-gaussian-with-matlab-with-given-height

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