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))
>>> A
array([[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()
>>> vmin
3
and for the maximum value, the max() function
>>> vmax = A.max()
>>> vmax
98
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,))
>>> A
array([4, 0, 4, 0, 2, 0, 2, 3, 2, 4])
>>> vmin = A.min()
>>> vmin
0
>>> np.where(A == vmin)
(array([1, 3, 5]),)
Example of how to plot the min on a matplotlib imshow figure
from pylab import figure, cm
import matplotlib.pyplot as plt
import numpy as np
def f(x1,x2):
return x1 * np.exp(-(x1**2+x2**2))
x1_min = -2.0
x1_max = 2.0
x2_min = -2.0
x2_max = 2.0
x1, 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 value
vmin = y.min()
#----- find min value indexes
min_indexes = np.where(y == vmin)
min1 = x1[ min_indexes[0] , min_indexes[1] ][0]
min2 = x2[ min_indexes[0] , min_indexes[1] ][0]
#----- plot
plt.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 |