Exemples de comment trouver les indices correspondants à la valeur maximum ou minimum dans une matrice en python en utilisant la fonction numpy where:
Soit, par exemple la matrice 2D suivante:
>>> 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]])
Trouver les valeurs min et max dans une matrice
Pour trouver la valeur min on peut faire comme ceci:
>>> vmin = A.min()>>> vmin3
et pour trouver la valeur max
>>> vmax = A.max()>>> vmax98
voir Comment trouver le maximum ou minimum d'une matrice avec numpy de python ?
Trouver les indices correspondants
Connaissant les valeurs min et max on peut alors trouver les indices avec la fonction numpy where.
Indices de la valeur minimum:
>>> np.where(A == vmin)(array([2]), array([2]))
Indices de la valeur maximum:
>>> np.where(A == vmax)(array([2]), array([0]))
Note: exemple avec une matrice présentant plusieurs min:
>>> 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]),)
la matrice A possède un minimum (ici 0) en trois places (1,3,5)
Exemple de cas: tracer le min sur une figure matplotlib

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()
Références
| Liens | Site |
|---|---|
| How to find the minimum value in a numpy matrix? | stackoverflow |
| numpy.where | docs.scipy.org |
| Sorting, searching, and counting | docs.scipy.org |
