% Example 9.2
% In this example, we show how to get a bona fide density histogram. The
% main difference is to normalize by dividing by the width of the bins. 

load galaxy
n = length(EastWest);
% Use Sturge's Rule to get the number of bins.
k = round(1 + log2(n));
% Bin the data.
[nuk,xk] = hist(EastWest,k);
% Get the width of the bins.
h = xk(2) - xk(1);
% Plot as a histogram.
bar(xk, nuk/(n*h), 1, 'w')
title('Density Histogram - Galaxy Data')
xlabel('Velocity')

% Now return an estimate at a point xo.
xo = 0;
% Find all of the bin centers less than xo.
ind = find(xk < xo);
% xo should be between these two bin centers.
b1 = xk(ind(end));
b2 = xk(ind(end)+1);
% Put it in the closer bin.
if (xo-b1) < (b2-xo)   % then put it in the 1st bin
   fhat = nuk(ind(end))/(n*h);
else
   fhat = nuk(ind(end)+1)/(n*h);
end


