fitting a gaussian curve to a bar graph

5 views (last 30 days)
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.

Accepted Answer

Rik
Rik on 8 Apr 2018
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 Comment
Rik
Rik on 9 Apr 2018
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Discrete Data Plots in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!