1 ## Copyright (C) 2003 Alberto Terruzzi <t-albert@libero.it>
3 ## This program is free software; you can redistribute it and/or modify it under
4 ## the terms of the GNU General Public License as published by the Free Software
5 ## Foundation; either version 3 of the License, or (at your option) any later
8 ## This program is distributed in the hope that it will be useful, but WITHOUT
9 ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
13 ## You should have received a copy of the GNU General Public License along with
14 ## this program; if not, see <http://www.gnu.org/licenses/>.
17 ## @deftypefn {Function File} histfit (@var{data}, @var{nbins})
19 ## Plot histogram with superimposed fitted normal density.
21 ## @code{histfit (@var{data}, @var{nbins})} plots a histogram of the values in
22 ## the vector @var{data} using @var{nbins} bars in the histogram. With one input
23 ## argument, @var{nbins} is set to the square root of the number of elements in
29 ## histfit (randn (100, 1))
32 ## @seealso{bar,hist, pareto}
35 ## Author: Alberto Terruzzi <t-albert@libero.it>
37 ## Created: 3 March 2004
39 function histfit (data,nbins)
41 if nargin < 1 || nargin > 2
45 if isvector (data) != 1
46 error ("data must be a vector.");
49 row = sum(~isnan(data));
52 nbins = ceil(sqrt(row));
55 [n,xbin]=hist(data,nbins);
56 if any(abs(diff(xbin,2)) > 10*max(abs(xbin))*eps)
57 error("histfit bins must be uniform width");
60 mr = nanmean(data); ## Estimates the parameter, MU, of the normal distribution.
61 sr = nanstd(data); ## Estimates the parameter, SIGMA, of the normal distribution.
62 x=(-3*sr+mr:0.1*sr:3*sr+mr)';## Evenly spaced samples of the expected data range.
63 [xb,yb] = bar(xbin,n);
64 y = normal_pdf(x,mr,sr.^2);
65 binwidth = xbin(2)-xbin(1);
66 y = row*y*binwidth; ## Normalization necessary to overplot the histogram.
67 plot(xb,yb,";;b",x,y,";;r-"); ## Plots density line over histogram.