【问题标题】:Numpy equivalent to MATLAB's histNumpy 相当于 MATLAB 的 hist
【发布时间】:2021-10-28 00:16:54
【问题描述】:

由于某种原因,Numpy 的 hist 总是返回比 MATLAB 的 hist 少一个 bin:

例如在 MATLAB 中:

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

给予:

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

但在 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))

给予:

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

如何获得与 MATLAB 相同的结果?

【问题讨论】:

标签: matlab numpy


【解决方案1】:

根据 dilayapici 在这篇文章中的回答,一个通用的解决方案(适用于您的示例)以与 Matlab 的 hist 相同的方式运行 Python 的 np.histogram,如下:

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)

输出:

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

【讨论】:

    【解决方案2】:

    首先我想解释一下这个问题。

    在 Phyton 中,它的运行方式如下:

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

    • 第一个 bin 等于 [1, 2)(包括 1,但不包括 2),因此 ==> Rep[0]=2

    • 第二个 bin 等于 [2, 3)(包括 2,但不包括 3),因此 ==> Rep[1]=4

    • 最后一个 bin 等于 [3, 4],其中包括 4。因此 ==> Rep[2] = 6

    在 MATLAB 中 hist() 函数运行如下:

    • 第一个 bin 等于 [1, 2)(包括 1,但不包括 2),因此 ==> Rep[0]=2

    • 第二个 bin 等于 [2, 3)(包括 2,但不包括 3),因此 ==> Rep[1]=4

    • 第三个 bin 等于 [3, 4)(包括 3,但不包括 4),因此 ==> Rep[2]=4

    • 最后一个 bin 等于 [4, ∞),因此 ==> Rep[3]=2

    现在如果你想在 Pyhton 中得到相同的结果,你必须在 Matlab 中使用不同的函数。这是histogram() 函数。我们可以决定“bins number”。

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

    你可以看到h.Values等于[2,4,6]。

    希望能帮到你:)

    【讨论】:

      猜你喜欢
      • 2012-05-21
      • 1970-01-01
      • 2011-03-13
      • 2023-03-17
      • 1970-01-01
      • 2010-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多