MATLAB: Fitting a normal distribution function to a set of data

curve fittinghistogramnormal distribution

Hi, I have a set of data, in the form of a histogram (with actual data also ready) and I want to fit a normal distribution curve on it. Is their an efficient way to do it?
Thanks

Best Answer

If you have the Statistics Toolbox, use the histfit function.
Otherwise, this works:
d = 2*randn(250,1)+20; % Created Data
binrs = min(d):(max(d)-min(d))/25:max(d); % Bin Definitions
knt = histc(d, binrs); % Histogram Counts
s = std(d); % Intial Parameter Estimate

m = mean(d); % Intial Parameter Estimate
% b(1) = mean, b(2) = std, b(3) = amplitude
pdfnrm = @(x,b) b(3) * 1./(b(2)*sqrt(2*pi)) .* exp(-((x-b(1)).^2./(2*b(2).^2)));
SSECF = @(b) sum((knt-pdfnrm(binrs,b)').^2); % Sum-Squared-Error Cost Function
[B,SSE] = fminsearch(SSECF, [m; s; 10]);
figure(1)
bar(binrs,knt,'g') % Plot Histogram
hold on
plot(binrs,pdfnrm(binrs,B),'r') % Plot Normal Distribution
hold off
grid