MATLAB: Fitting a gaussian curve to a bar graph

barplotgaussianhistogram

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.

Best Answer

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)