function [s,nu] = chi2uniform(x,m)

x = x(:) ;              % Turn 2D matrix into vector
[n,foobar] = size(x) ;  % Get the length of the vector
h = histcounts(x,'BinMethod','integers') ; % Get frequencies
if nargin < 2,
   m = length(h) ;      % Get the size of the sample space
end
nu = m - 1 ;            % Number of degrees of freedom
avg = n/m ;             % Expected frequency

y = (h-avg) .^ 2 ./ avg ;  % Calculate every term of the chi2 statistic
s = sum(y) ;               % Add the terms to get the chi2 statistic
