简体   繁体   English

将 Matlab hist() 与 Numpy histogram() 匹配

[英]Match Matlab hist() with Numpy histogram()

I have read this and this , plus some related SO questions like this .我已经阅读了这个这个,以及一些像这样的相关 SO 问题。 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.我尝试在 Matlab 中复制 hist() 函数,得到不同维度的结果,导致内部值不同。 I am aware of bin-center vs bin-edge, I still want to match Matlab results.我知道 bin-center vs bin-edge,我仍然想匹配 Matlab 结果。

Matlab: 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: 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: 手动计算bin-centers:

>>> 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 : 使用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:根据我在https://stackoverflow.com/a/69742169/5481421 中的回答,您可以:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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