簡體   English   中英

將 Matlab hist() 與 Numpy histogram() 匹配

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

我已經閱讀了這個這個,以及一些像這樣的相關 SO 問題。 還是想不出解決辦法。

我嘗試在 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

我當然可以編寫自己的函數,但是如果有內置的東西,我會盡量避免重新發明輪子。

手動計算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])

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

對於此問題的未來搜索:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM