Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find index of min value in a matrix

I've a 2-Dim array containing the residual sum of squares of a given fit (unimportant here).

RSS[i,j] = np.sum((spectrum_theo - sp_exp_int) ** 2)

I would like to find the matrix element with the minimum value AND its position (i,j) in the matrix. Find the minimum element is OK:

RSS_min = RSS[RSS != 0].min()

but for the index, I've tried:

ij_min = np.where(RSS == RSS_min)

which gives me:

ij_min =  (array([3]), array([20]))

I would like to obtain instead:

ij_min = (3,20)

If I try :

ij_min = RSS.argmin()

I obtain:

ij_min = 0,

which is a wrong result.

Does it exist a function, in Scipy or elsewhere, that can do it? I've searched on the web, but I've found answers leading only with 1-Dim arrays, not 2- or N-Dim.

Thanks!

like image 684
ariel67 Avatar asked Sep 05 '25 03:09

ariel67


2 Answers

The easiest fix based on what you have right now would just be to extract the elements from the array as a final step:

# ij_min = (array([3]), array([20]))
ij_min = np.where(RSS == RSS_min)
ij_min = tuple([i.item() for i in ij_min])
like image 121
Christian Avatar answered Sep 07 '25 20:09

Christian


You can combine argmin with unravel_index.

For example, here's an array RSS:

In [123]: np.random.seed(123456)

In [124]: RSS = np.random.randint(0, 99, size=(5, 8))

In [125]: RSS
Out[125]: 
array([[65, 49, 56, 43, 43, 91, 32, 87],
       [36,  8, 74, 10, 12, 75, 20, 47],
       [50, 86, 34, 14, 70, 42, 66, 47],
       [68, 94, 45, 87, 84, 84, 45, 69],
       [87, 36, 75, 35, 93, 39, 16, 60]])

Use argmin (which returns an integer that is the index in the flattened array), and then pass that to unravel_index along with the shape of RSS to convert the index of the flattened array into the indices of the 2D array:

In [126]: ij_min = np.unravel_index(RSS.argmin(), RSS.shape)

In [127]: ij_min
Out[127]: (1, 1)

ij_min itself can be used as an index into RSS to get the minimum value:

In [128]: RSS_min = RSS[ij_min]

In [129]: RSS_min
Out[129]: 8
like image 44
Warren Weckesser Avatar answered Sep 07 '25 19:09

Warren Weckesser