Friday, October 12, 2012

Find the location and value of an extremum of a matrix

I needed to find the location and the value of the maximum or minimum of a 2-d array. Here is how I did it.

A Simple way

Assume that  the data is stored in a 2-d array A.
index =  A.argmax()  #use argmin() to get the minimum
row = index / A.shape[1]
col  = index % A.shape[1]

# The following two statements will give you the value of the maximum

A.max() 
A[row][col] 


Another way

I saw another solution on Stack Overflow. Again, is A is my array:
import numpy as np
b=np.where(A==np.max())
row = b[0][0]
col  = b[1][0]


Get the location of the maximum/minimum in each row

A.argvmax(axis=1) or A.argvmin(axis=1)
The result is an array of indices indicating the column number where the maximum or minimum occurs. So the size of this array is the same size as your rows in A (A.shape[0])
 

Get the location of the maximum/minimum in each column

A.argvmax(axis=0) or A.argvmin(axis=0)
The result is an array of indices indicating the row number where the maximum or minimum occurs. So the size of this array is the same size as your columns  in A (A.shape[1]))

No comments:

Post a Comment