]> Creatis software - CreaPhase.git/blob - octave_packages/statistics-1.1.3/histfit.m
Add a useful package (from Source forge) for octave
[CreaPhase.git] / octave_packages / statistics-1.1.3 / histfit.m
1 ## Copyright (C) 2003 Alberto Terruzzi <t-albert@libero.it>
2 ##
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
6 ## version.
7 ##
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
11 ## details.
12 ##
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/>.
15
16 ## -*- texinfo -*-
17 ## @deftypefn {Function File} histfit (@var{data}, @var{nbins})
18 ##
19 ## Plot histogram with superimposed fitted normal density.
20 ##
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
24 ## data. 
25 ##
26 ## Example
27 ##
28 ## @example
29 ## histfit (randn (100, 1))
30 ## @end example
31 ##
32 ## @seealso{bar,hist, pareto}
33 ## @end deftypefn
34
35 ## Author: Alberto Terruzzi <t-albert@libero.it>
36 ## Version: 1.0
37 ## Created: 3 March 2004
38
39 function histfit (data,nbins)
40
41   if nargin < 1 || nargin > 2
42     print_usage;
43   endif
44
45   if isvector (data) != 1
46     error ("data must be a vector.");
47   endif
48
49   row = sum(~isnan(data));
50
51   if nargin < 2
52     nbins = ceil(sqrt(row));
53   endif
54
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");
58   endif
59
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.
68
69 endfunction
70