fitting a gaussian curve to a bar graph
8 次查看(过去 30 天)
显示 更早的评论
I wanted to fit a gaussian curve (by specifying a mean and variance) to the following bar plot. How can I do it? And how will know if this is a good fit?
Thanks for your insights.
0 个评论
采纳的回答
Rik
2018-4-8
I doubt your distribution is actually normal, but you can use the code below to fit a Gaussian curve, without even the curve fitting toolbox. What goodness of fit parameter suits you, will depend on your situation.
%generate data for bar plot
data=randn(1,10000)*5;
[N,edges] = histcounts(data,30);
centers=edges(2:end)-(edges(2)-edges(1));
%normalize data
N=N/trapz(centers,N);
figure(1),clf(1)
bar(centers,N)
f_gauss=@(mu,sigma,x) 1./sqrt(2*pi*sigma.^2)*exp(-(x-mu).^2./(2*sigma.^2));
y = @(b,x) f_gauss(b(1),b(2),x);% Objective function
x = centers; yx = N;% Normalized sampled values
OLS = @(b) sum((y(b,x) - yx).^2);% Ordinary Least Squares cost function
opts = optimset('MaxFunEvals',50000, 'MaxIter',10000);
result = fminsearch(OLS, [0 5], opts);% Use 'fminsearch' to minimise the 'OLS' function
trendfitlabel=sprintf('\\mu=%.2f, \\sigma=%.2f',result);
%add the fitted distribution to the plot
new_centers=linspace(min(centers),max(centers),10*numel(centers));
hold on
plot(new_centers,f_gauss(result(1),result(2),new_centers))
hold off
legend('data',trendfitlabel)
1 个评论
Rik
2018-4-9
Did this suggestion solve your problem? If so, please consider marking it as accepted answer. It will make it easier for other people with the same question to find an answer, as well as give me reputation points. If this didn't solve your question, please comment with what problems you are still having.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Discrete Data Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!