Numpy equivalent to MATLAB's hist

Viewed 246

For some reason Numpy's hist always returns one less bin than MATLAB's hist:

for example in MATLAB:

x = [1,2,2,2,1,4,4,2,3,3,3,3];
[Rep,Val] = hist(x,unique(x));

gives:

Rep = [2 4 4 2]
Val = [1 2 3 4]

but in Numpy:

import numpy as np
x = np.array([1,2,2,2,1,4,4,2,3,3,3,3])
Rep, Val = np.histogram(x,np.unique(x))

gives:

>>>Rep
array([2, 4, 6])
>>>Val
array([1, 2, 3, 4])

How can I get identical results ti MATLAB's?

2 Answers

Based on dilayapici's answer on this post, a general solution (applied to your example) to run Python's np.histogram in the same way as Matlab's hist, is the following:

x = np.array([1,2,2,2,1,4,4,2,3,3,3,3])
# Convert the bin centers given in Matlab to bin edges needed in Python.
numBins = len(np.unique(x))
bins = np.linspace(np.amin(x), np.amax(x), numBins)
# Edit the 'bins' argument of `np.histogram` by just putting '+inf' as the last element.
bins = np.concatenate((bins, [np.inf]))
Rep, Val = np.histogram(x, bins)

Output:

Rep
array([2, 4, 4, 2], dtype=int64)

Firstly I want to explain this problem.

In Phyton it is running like:

np.unique(x) = [1, 2, 3, 4] so,

  • The first bin is equal to [1, 2) (including 1, but excluding 2) and therefore ==> Rep[0]=2

  • The second bin is equal to [2, 3) (including 2, but excluding 3) and therefore ==> Rep[1]=4

  • The last bin is equal to [3, 4], which includes 4. Therefore ==> Rep[2] = 6

In MATLAB hist() function is running like:

  • The first bin is equal to [1, 2) (including 1, but excluding 2) and therefore ==> Rep[0]=2

  • The second bin is equal to [2, 3) (including 2, but excluding 3) and therefore ==> Rep[1]=4

  • The third bin is equal to [3, 4) (including 3, but excluding 4) and therefore ==> Rep[2]=4

  • The last bin is equal to [4, ∞) and therefore ==> Rep[3]=2

Now If you want same result in Pyhton, you have to use different function in Matlab. This is histogram() function. We can decide "bins number".

x = [1,2,2,2,1,4,4,2,3,3,3,3];
nbins=3 ;
h= histogram(x,nbins);
h.Values 

You can see h.Values equals to [2,4,6].

I hope, I could help :)

Related