Examples of how to find the indexes of the minimum or maximum value(s) in a matrix using python and the numpy function called where:
Let's consider the following 2D matrix:
>>> import numpy as np>>> A = np.random.randint(100, size=(4, 4))>>> Aarray([[73, 37, 6, 21],[16, 53, 77, 44],[98, 95, 3, 29],[77, 67, 87, 86]])
Find min and max values
First, to find the minimum value, a solution is to use the numpy function min()
>>> vmin = A.min()>>> vmin3
and for the maximum value, the max() function
>>> vmax = A.max()>>> vmax98
see How to find the minimum or maximum value in a matrix with python ?
Find corresponding indexes
Now, it is possible to retrieve the indexes using the numpy function where.
minimum value indexes
>>> np.where(A == vmin)(array([2]), array([2]))
maximum value indexes:
>>> np.where(A == vmax)(array([2]), array([0]))
Note: another example with a matrix with several minimum:
>>> import numpy as np>>> A = np.random.randint(5, size=(10,))>>> Aarray([4, 0, 4, 0, 2, 0, 2, 3, 2, 4])>>> vmin = A.min()>>> vmin0>>> np.where(A == vmin)(array([1, 3, 5]),)
Example of how to plot the min on a matplotlib imshow figure

from pylab import figure, cmimport matplotlib.pyplot as pltimport numpy as npdef f(x1,x2):return x1 * np.exp(-(x1**2+x2**2))x1_min = -2.0x1_max = 2.0x2_min = -2.0x2_max = 2.0x1, x2 = np.meshgrid(np.arange(x1_min,x1_max, 0.1), np.arange(x2_min,x2_max, 0.1))y = f(x1,x2)#----- find min valuevmin = y.min()#----- find min value indexesmin_indexes = np.where(y == vmin)min1 = x1[ min_indexes[0] , min_indexes[1] ][0]min2 = x2[ min_indexes[0] , min_indexes[1] ][0]#----- plotplt.imshow(y,extent=[x1_min,x1_max,x2_min,x2_max], cmap=cm.jet, origin='lower')plt.colorbar()plt.scatter(min1,min2,color='r',marker='x')plt.savefig("plot_minimum_imshow.png")#plt.show()
References
| Links | Site |
|---|---|
| How to find the minimum value in a numpy matrix? | stackoverflow |
| numpy.where | docs.scipy.org |
| Sorting, searching, and counting | docs.scipy.org |
