fitting a gaussian curve to a bar graph

8 Ansichten (letzte 30 Tage)
CLARK KENDRICK GO
CLARK KENDRICK GO am 8 Apr. 2018
Kommentiert: Rik am 9 Apr. 2018
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.

Akzeptierte Antwort

Rik
Rik am 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 Kommentar
Rik
Rik am 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Discrete Data Plots finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by