function chisq = ChiSquaredTest(data,propexpectedinbin,bincentre)
% chisq = ChiSquaredTest(data,model,bincentre)
% Chi-sq statistic
% data and bincentres are arrays.
% data is the data (obviously), and bincentres is an array
% defining the bins you want to test it against.
% Propexpectedinbin tells you what proportion are expected in each bin

nfoundinbin = hist(data,bincentre);
% If some of the data falls outside the bins, it is lumped into the appropriate end bin.

nbins = length(bincentre);
% FInally evaluate chi-sq:
nexpectedinbin = propexpectedinbin .* length(data);
if ~isempty(find(nexpectedinbin==0))
	chisq=Inf;
else
	chisq = sum( (nfoundinbin-nexpectedinbin).^2./nexpectedinbin );
end

