ver=version;

assert2 = @(x,y) assert(all(all(x-y<1e-10)));
uint8 = @(x) x;

[nn,xx] = hist ([1:4], 3);
assert2 (xx, [1.5,2.5,3.5]);
assert2 (nn, [2,1,1]);
[nn,xx] = hist ([1:4]', 3);
assert2 (xx, [1.5,2.5,3.5]);
assert2 (nn, [2,1,1]);
[nn,xx] = hist ([1 1 1 NaN NaN NaN 2 2 3],[1 2 3]);
assert2 (xx, [1,2,3]);
assert2 (nn, [3,2,1]);
[nn,xx] = hist ([1 1 1 NaN NaN NaN 2 2 3],[1 2 3], 6);
assert2 (xx, [1,2,3]);
assert2 (nn, [3,2,1]);
[nn,xx] = hist ([[1:4]', [1:4]'], 3);
assert2 (xx, [1.5;2.5;3.5]);
assert2 (nn, [ [2,1,1]',[2,1,1]' ]);
for n = [10, 30, 100, 1000]
  assert2 (sum (hist ([1:n], n)), n);
  assert2 (sum (hist ([1:n], [2:n-1])), n);
  assert2 (sum (hist ([1:n], [1:n])), n);
  assert2 (sum (hist ([1:n], 29)), n);
  assert2 (sum (hist ([1:n], 30)), n);
end
assert2 (hist (1,1), 1)
assert2 (size (hist (randn (750,240), 200)), [200,240])

% Test bug #42394
assert2 (isempty (hist (rand (10,2), 0:5, 1)), false)
assert2 (isempty (hist (rand (10,2), 0:5, [1 1])), false)

% Test bug #47707
y = [1  9  2  2  9  3  8  9  1  7  1  1  3  2  4  4  8  2  1  9  4  1 ...
     2  3  1  1  6  5  5  3  9  9  1  1  8  7  7  2  4  1];
[n, x] = hist (y, 10);
[nn, xx] = hist (uint8 (y), 10);
assert2 (nn, n)
assert2 (xx, x)

% test again with N > 30 because there's a special case for it
[n, x] = hist (y, 35);
[nn, xx] = hist (uint8 (y), 35);
assert2 (nn, n)
assert2 (xx, x)

% Test logical input
y = [0  1  0  0  1  0  1  1  0  1  0  0  0  0  0  0  1  0];
[n, x] = hist (y, 10);
[nn, xx] = hist (logical (y), 10);
assert2 (nn, n)
assert2 (xx, x)

% test again with N > 30 because there's a special case for it
[n, x] = hist (y, 35);
[nn, xx] = hist (logical (y), 35);
assert2 (nn, n)
assert2 (xx, x)

% Second output argument must be of class single if data is class single.
[nn, xx]=hist(rand(10, 1, 'single'));
assert (isa(single(xx),'single'));

% Handle second argument correctly, even when it's class integer
y = [2.4 2.5 2.6 5.4 5.5 5.6];
n = [2  3  1];
x = [1  4  7];
[nn, xx] = hist (y, uint8 ([1 4 7]));
assert2 (nn, n)
assert2 (xx, x)
y = [2.4 2.5 2.6 5.4 5.5 5.6];
s = (5.6 - 2.4) / 6;
x = [2.4+s 4.0 5.6-s];
n = [3 0 3];
[nn, xx] = hist (y, 3);
assert2 (nn, n)
assert2 (xx, x)

[nn, xx] = hist (y, uint8 (3));
assert2 (nn, n)
assert2 (xx, x)
[nn, xx] = hist (y, single (3));
assert2 (nn, n)
% single bug fixed in Matlab >= 2014b
if (str2num(ver(1))==8 & str2num(ver(3))>=3)
  assert2 (xx, x)
  fprintf('"assert2 (xx, single (x))" bug fixed\n');
else
  assert2 (xx, single (x)) 
  fprintf('"assert2 (xx, single (x))" bug present\n');
end

% Check Matlab for compatibility
[nn,xx] = hist ([1:8], [1:2:7]);
assert2 (xx, [1:2:7]);
assert2 (nn, 2*ones(1,4));
[nn,xx] = hist ([1:8], [1:2:7]');
assert2 (xx, [1:2:7]');
assert2 (nn, 2*ones(1,4));
[nn,xx] = hist ([1:8], [1 5; 3 7]);
assert2 (xx, [1 5; 3 7]);
assert2 (nn, 2*ones(1,4));
[nn,xx] = hist ([1:8], [1 5 3 7]);
assert2 (xx, [1 5 3 7]);
assert2 (nn, [3 1 1 3]);