pythonmatrixscipy

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!


Solution

  • 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])