简体   繁体   中英

Match Matlab hist() with Numpy histogram()

I have read this and this , plus some related SO questions like this . Still can not figure out the solution.

I try to replicate the hist() function in Matlab, I get the result of different dimensions, that causing the values inside to be different. I am aware of bin-center vs bin-edge, I still want to match Matlab results.

Matlab:

a = [1,2,3];
[w,t] = hist(a);
w = [1, 0, 0, 0, 1, 0, 0, 0, 0, 1]
t = [1.1, 1.3, 1.5, 1.7, 1.9, 2.1, 2.3, 2.5, 2.7, 2.9]
length(t) = 10

Python:

a = [1,2,3]
w,t = histogram(a)
w = [1, 0, 0, 0, 0, 1, 0, 0, 0, 1]
t = [1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0]
len(t) = 11

I can of course code my own function, but I am trying to avoid wheel re-invention if there is something built-in.

Calculate the bin-centers manually:

>>> t = np.array([1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0])
>>> t[:-1] + ((t[1:] - t[:-1])/2)
array([ 1.1,  1.3,  1.5,  1.7,  1.9,  2.1,  2.3,  2.5,  2.7,  2.9])

or even easier with np.diff :

>>> t[:-1] + np.diff(t)/2
array([ 1.1,  1.3,  1.5,  1.7,  1.9,  2.1,  2.3,  2.5,  2.7,  2.9])

For future searches on this issue:

Based on my answer in https://stackoverflow.com/a/69742169/5481421 , you can do:

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

Output:

w
array([1, 0, 0, 0, 1, 0, 0, 0, 0, 1], dtype=int64)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM