【问题标题】:Match Matlab hist() with Numpy histogram()将 Matlab hist() 与 Numpy histogram() 匹配
【发布时间】:2017-01-26 08:45:39
【问题描述】:

我已阅读 this 和 this,以及一些相关的 SO 问题,例如 this。还是想不出解决办法。

我尝试在 Matlab 中复制 hist() 函数,我得到了不同维度的结果,导致里面的值不同。我知道 bin-center vs bin-edge,我仍然想匹配 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:

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

我当然可以编写自己的函数,但如果有内置的东西,我会尽量避免重新发明轮子。

【问题讨论】:

  • 我不懂 Python 所以帮不上你的忙,但请注意:不建议使用hist,改用histogram。
  • @Mikhail_Sam 哦错字,我已经将它导入为“从 numpy 导入直方图作为 hist”。现已修复,谢谢。

标签: python matlab numpy


【解决方案1】:

手动计算 bin 中心:

>>> 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])

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])

【讨论】:

  • 注意W也不同,因为bin定义不同。
  • 不确定您是否可以对此做任何事情,因为我不确定差异来自哪里。 numpy.histogram 使用“(最右边的)半开箱”,matlab 文档没有说明这一点。
【解决方案2】:

对于这个问题的未来搜索:

根据我在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)

输出:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-16
    • 2013-07-16
    • 2015-06-02
    相关资源
    最近更新 更多