How to find the minimum or maximum value in a matrix with python ?

Published: April 22, 2019

DMCA.com Protection Status

Examples of how to find the minimum and maximum values in a matrix using numpy and python:

Approach 1:

To find the minimum and maximum values in an array, a solution is to use the numpy functions max() and min():

>>> import numpy as np
>>> A = np.array(([2,7,-1],[1,9,8],[-1,5,6]))
>>> A
array([[ 2,  7, -1],
          [ 1,  9,  8],
          [-1,  5,  6]])
>>> np.min(A)
-1
>>> np.max(A)
9

Approach 2:

Another solution is to do :

>>> A.min()
-1
>>> A.max()
9

The advantage is to be able to mask some elements by adding one or multiple conditions, example:

>>> A[A>2].min()
5

Another example:

>>> A[(A>2) & (A<9)].max()
8

References