Requires an elegant numpy argmin solution.

In python, to find the index of the minimum value of an array, I use y = numpy.argmin(someMat)

Can I find the minimum value of this matrix so that it does not lie in a given range in a neat way?

+3
source share
2 answers

"Can I find the minimum value of this matrix so that it does not lie in a given range in a neat way?"

If you care only about the minimum value that satisfies a certain condition, and not a 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 need a location via argmin, then this is a bit more complicated, 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 is reversed here, since the mask is True for excluded values, not incoming ones.


: , " " , , x, y, ( , ):

>>> 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

, . [ mgrid; , !]

: ^), , , , 3x3 .

+7

, , :

Argmin :

>>> from numpy import *
>>> a = array( [2,3,4] )
>>> argmin(a)
0
>>> print a[argmin(a)]
2

:

>>> b=array( [[6,5,4],[3,2,1]] )
>>> argmin(b)
5
>>> print b[argmin(b)]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: index out of bounds

. , argmin ( ​​ argmax) - n- 1- .

, ravel:

>>> print b
[[6 5 4]
 [3 2 1]]
>>> ravel(b)
array([6, 5, 4, 3, 2, 1])

ravel argmin, :

>>> print ravel(b)[argmin(b)]
+4

All Articles