Why does numpy.histogram (Python) omit one element compared to hist in Matlab?

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

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

where Isb is a 1D array of size 2048000. N is output as an array of 1D type 301.

My Python code looks like this:

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

but the Python N outputs are a 300 element 1D array in which the last element from Matlab N is left.

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

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

 loc = X < -0.75 I = N[loc].argmax() 
+4
source share
2 answers

Notice that in matlab hist(x, vec) vec defines bin centers , and in matlab histc(x, vec) vec defines bin edges of the histogram. Numpy Bar Graph works with bin edges . Is the difference important to you? It should be easy to convert from one to another, and you might have to add an extra Inf to the end of the bin edges so that it can return an extra bit. In a more or less similar way (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 

Of course, it does not cover all the edges that matlab hist provides, but you get the idea.

+4
source

As stated above, bin centers are set in matlab -3: 0.01: 0, namely 301. What you do in numpy indicates the edges of the bin so that it will be one bit less than in matlab.

Therefore, you can either go from hist to histc in matlab, or make sure that you apply the same buffer edges in numpy. In this special case (equidistant bins) you can also use numpy as follows:

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

In this case: n_bins out of 301 and (xmin, xmax) being (-3.005,0.005) should be equivalent to matlab hist.

See also:

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

0
source

Source: https://habr.com/ru/post/1495387/


All Articles