]> Creatis software - CreaPhase.git/blob - octave_packages/plot-1.1.0/hist2d.m
Add a useful package (from Source forge) for octave
[CreaPhase.git] / octave_packages / plot-1.1.0 / hist2d.m
1 ## Copyright (C) 2006 Paul Kienzle <pkienzle@users.sf.net>
2 ## This program is in the public domain
3
4 ## -*- texinfo -*-
5 ## @deftypefn {Function File} {[@var{counts}, @var{xbins}, @var{ybins}] =} hist2d ([@var{x}, @var{y}], @var{xbins}, @var{ybins}, @var{norm})
6 ## Produce a 2D histogram.
7 ##
8 ## Points xi,yi are stored in a 2-column array.
9 ## If ybins is missing, use xbins.
10 ## If bins is a scalar, use that many bins.
11 ## If bins is a vector, it represents bin edges.
12 ##
13 ## @end deftypefn
14
15 function [ret_counts, xbins, ybins] = hist2d(M,xbins,ybins)
16
17   if nargin < 1 && nargin > 3
18     print_usage
19   end
20
21   lo = min(M);
22   hi = max(M);
23   if nargin == 1
24     ybins = xbins = 10;
25   elseif nargin == 2
26     ybins = xbins;
27   endif
28
29   # If n bins, find centers based on n+1 bin edges
30   if isscalar(xbins) 
31     xbins = linspace(lo(1),hi(1),xbins+1);
32     xbins = (xbins(1:end-1)+xbins(2:end))/2;
33   end
34   if isscalar(ybins)
35     ybins = linspace(lo(2),hi(2),ybins+1); 
36     ybins = (ybins(1:end-1)+ybins(2:end))/2;
37   end
38
39   xcut = (xbins(1:end-1)+xbins(2:end))/2;
40   ycut = (ybins(1:end-1)+ybins(2:end))/2;
41   xidx = lookup(xcut,M(:,1))+1;
42   yidx = lookup(ycut,M(:,2))+1;
43   counts = sparse(xidx,yidx,1,length(xbins),length(ybins),'sum');
44
45   if nargout
46     ret_counts = full(counts');
47   else
48     mesh(xbins,ybins,full(counts'));
49   end
50 endfunction