簡體   English   中英

與matlab中的hist相比,為什么numpy.histogram(Python)會遺漏一個元素?

[英]Why does numpy.histogram (Python) leave off one element as compared to hist in Matlab?

我試圖將一些Matlab代碼轉換為Python,並且Matlab代碼如下所示:

[N,X] = hist(Isb*1e6, -3:0.01:0)

其中Isb是一個2048000元素的1D陣列。 N作為301元素1D陣列輸出。

我的Python代碼如下:

import numpy as np
N,X = np.histogram(Isb*1e6,np.array(-3,0.01,0.01))

但是N Python輸出是一個300元素的1D數組,其中Matlab N的最后一個元素沒有了。

有沒有辦法復制Matlab更准確的內容?

我需要N和X相同的大小,以便我可以這樣做:

loc = X < -0.75
I   = N[loc].argmax()

請注意,在matlab的hist(x, vec) ,vec區分bin- center,而在matlab histc(x, vec) vec定義直方圖的bin-edge Numpy的直方圖似乎適用於邊緣 這種差異對你很重要嗎? 它應該很容易從一個轉換到另一個,你可能需要在bin-edge的末尾添加一個額外的Inf來讓它返回你想要的額外bin。 或多或少像這樣(未經測試):

import numpy as np

def my_hist(x, bin_centers):
    bin_edges = np.r_[-np.Inf, 0.5 * (bin_centers[:-1] + bin_centers[1:]), 
        np.Inf]
    counts, edges =  np.histogram(x, bin_edges)
    return counts

當然,它並沒有涵蓋matlab的hist提供的所有邊緣情況,但是你明白了。

如上所述,在matlab -3:0.01:0中指定了bin中心,即301.你在numpy中做的是指定bin-edges,所以這將比matlab中的bin少一個bin。

因此,您可以在matlab中從hist移動​​到histc,或者確保在numpy中應用相同的bin-edge。 在這種特殊情況下(等距離箱)你也可以像這樣使用numpy:

N,X = np.histogram(x, bins = n_bins, range = (xmin, xmax))

在這種情況下:301的n_bins和(-3.005,0.005)的(xmin,xmax)應該等同於matlab的hist。

也可以看看:

http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html

暫無
暫無

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

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