为什么numpy.histogram(Python)与Matlab中的hist相比只留下一个元素? [英] Why does numpy.histogram (Python) leave off one element as compared to hist in Matlab?

查看:390
本文介绍了为什么numpy.histogram(Python)与Matlab中的hist相比只留下一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一些Matlab代码转换为Python,而Matlab代码如下所示:

I am trying to convert some Matlab code to Python, and the Matlab code looks like:

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

其中,Isb是2048000元素的1D数组. N作为301元素一维数组输出.

where Isb is a 2048000 element 1D array. N is output as a 301 element 1D array.

我的Python代码如下:

My Python code looks like:

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

但是N个Python输出是一个300元素的1D数组,其中Matlab N的最后一个元素被保留.

but the N Python outputs is a 300 element 1D array where the last element from the Matlab N is left off.

有没有一种方法可以更准确地复制Matlab的功能?

Is there a way to replicate what Matlab does more accurately?

我需要N和X的大小相同,这样我才能做到:

I need N and X to be the same size so that I can do this:

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

推荐答案

请注意,在matlab的hist(x, vec)中,vec定义了 bin-centers ,而在matlab histc(x, vec)中,vec定义了 bin-edges . Numpy的直方图似乎适用于 bin-edges .这个区别对您重要吗?从一个到另一个的转换应该很容易,并且您可能必须在垃圾箱边缘的末端添加一个额外的Inf,以使其返回所需的额外垃圾箱.或多或少像这样(未经测试):

Note that in matlab's hist(x, vec), vec difines the bin-centers, while in matlab histc(x, vec) vec defines the bin-edges of the histogram. Numpy's histogram seems to work with bin-edges. Is this difference important to you? It should be easy to convert from one to the other, and you might have to add an extra Inf to the end of the bin-edges to get it to return the extra bin you want. More or less like this (untested):

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提供的所有边缘情况,但是您明白了.

For sure it does not cover all the edge-cases that matlab's hist provides, but you get the idea.

这篇关于为什么numpy.histogram(Python)与Matlab中的hist相比只留下一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆