1

I have an n*n array, and I want to find the min in the array, and get the index of the min in [x,y] format

Of course, this can be done using for loops and using temporary variables, but I am looking for a more sophisticated process to do this.

Example -

    [[1,2,8],
     [7,4,2],
     [9,1,7],
     [0,1,5],
     [6,-4,3]]

I should get the following output -

    Output-
    Min = -4
    Index = [4,1]

Can I implement something similar?

TIA.

1 Answer 1

2

Global minimum value and index

Flatten the array, get the argmin index. Get the corresponding row-col indices from it with np.unravel_index. Also, index into the flattened array with the earlier obtained flattened argmin index for the minimum value.

def smallest_val_index(a):
    idx = a.ravel().argmin()
    return a.ravel()[idx], np.unravel_index(idx, a.shape)

Sample run -

In [182]: a
Out[182]: 
array([[ 1,  2,  8],
       [ 7,  4,  2],
       [ 9,  1,  7],
       [ 0,  1,  5],
       [ 6, -4,  3]])

In [183]: val, indx = smallest_val_index(a)

In [184]: val
Out[184]: -4

In [185]: indx
Out[185]: (4, 1)

Global maximum value and index

Similarly, to get the global maximum value, use argmax -

def largest_val_index(a):
    idx = a.ravel().argmax()
    return a.ravel()[idx], np.unravel_index(idx, a.shape)

Sample run -

In [187]: a
Out[187]: 
array([[ 1,  2,  8],
       [ 7,  4,  2],
       [ 9,  1,  7],
       [ 0,  1,  5],
       [ 6, -4,  3]])

In [188]: largest_val_index(a)
Out[188]: (9, (2, 0))
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.