Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i replicate this matlab function in numpy?

[A,I] = histc([0.9828    0.4662    0.5245    0.9334    0.2163],[0.0191    0.2057    0.2820    0.2851    1.0000])

That is the MATLAB code with the results:

A =

     0     1     0     4     0


I =

     4     4     4     4     2

What I need is I. I've tried using np.histogram but it gives me this:

>>> a,b = np.histogram([0.9828 ,   0.4662 ,   0.5245 ,   0.9334 ,   0.2163],[0.0191   , 0.2057   , 0.2820  ,  0.2851  ,  1.0000])
>>> a
array([0, 1, 0, 4])
>>> b
array([ 0.0191,  0.2057,  0.282 ,  0.2851,  1.    ])

I want to get the bins that each element in my array/matrix goes into.

like image 212
power2 Avatar asked Jun 10 '26 17:06

power2


2 Answers

What you are looking for is numpy.digitize:

Return the indices of the bins to which each value in input array belongs.

>>> a = np.digitize([0.9828 ,   0.4662 ,   0.5245 ,   0.9334 ,   0.2163],[0.0191   , 0.2057   , 0.2820  ,  0.2851  ,  1.0000])
>>> print(a)
[4 4 4 4 2]
like image 193
TheBlackCat Avatar answered Jun 12 '26 07:06

TheBlackCat


A correct python implementation of matlab's histc is the following:

import numpy as np

def histc(x, binranges):
  indices = np.searchsorted(binranges, x)
  return np.mod(indices+1, len(binranges)+1)
like image 36
Aleph Avatar answered Jun 12 '26 07:06

Aleph