Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy argmin elegant solution required.

In python to find the index of the minimum value of the array I usey = numpy.argmin(someMat)

Can i find the minimum value of this matrix such that it does not lie within a specified range in a neat way?

like image 703
JustInTime Avatar asked Feb 15 '26 02:02

JustInTime


1 Answers

"Can i find the minimum value of this matrix such that it does not lie within a specified range in a neat way?"

If you only care about the minimum value satisfying some condition and not the location, then

>>> numpy.random.seed(1)
>>> m = numpy.random.randn(5.,5.)
>>> m
array([[ 1.62434536, -0.61175641, -0.52817175, -1.07296862,  0.86540763],
       [-2.3015387 ,  1.74481176, -0.7612069 ,  0.3190391 , -0.24937038],
       [ 1.46210794, -2.06014071, -0.3224172 , -0.38405435,  1.13376944],
       [-1.09989127, -0.17242821, -0.87785842,  0.04221375,  0.58281521],
       [-1.10061918,  1.14472371,  0.90159072,  0.50249434,  0.90085595]])
>>> m[~ ((m < 0.5) | (m > 0.8))].min()
0.50249433890186823

If you do want the location via argmin, then that's a bit trickier, but one way is to use masked arrays:

>>> numpy.ma.array(m,mask=((m<0.5) | (m > 0.8))).argmin()
23
>>> m.flat[23]
0.50249433890186823

Note that the condition here is flipped, as the mask is True for the excluded values, not the included ones.


Update: it appears that by "within a specified range" you don't mean the minimum value isn't within some bounds, but that you want to exclude portions of the matrix from the search based on the x,y coordinates. Here's one way (same matrix as before):

>>> xx, yy = numpy.indices(m.shape)
>>> points = ((xx == 0) & (yy == 0)) | ((xx > 2) & (yy < 3))
>>> points
array([[ True, False, False, False, False],
       [False, False, False, False, False],
       [False, False, False, False, False],
       [ True,  True,  True, False, False],
       [ True,  True,  True, False, False]], dtype=bool)
>>> m[points]
array([ 1.62434536, -1.09989127, -0.17242821, -0.87785842, -1.10061918,
        1.14472371,  0.90159072])
>>> m[points].min()
-1.1006191772129212

with the corresponding masked array variant if you need the locations. [Edited to use indices instead of mgrid; I'd actually forgotten about it until it was used in another answer today!]

If I'm still wrong :^) and this also isn't what you're after, please edit your question to include a 3x3 example of your desired input and output.

like image 53
DSM Avatar answered Feb 16 '26 16:02

DSM