How do you find the minimum or maximum of an array?

Advertisement: In 2012, I published the book A Hands-On Introduction to Using Python in the Atmospheric and Oceanic Sciences. If you're new to Python, you may find it useful!

Although this should be a trivial task, things are complicated by the fact that of the multiple min/max functions you can use, each behaves slightly differently.

The built-in Python functions `min`

and `max`

will work on a sequence or a series of arguments. However,
you will get a type error if you try it on a single scalar, so
you have to test ahead of time whether a single-argument call
is operating on a sequence. Additionally, if the sequence is
an array of more than one dimension, `min`

and `max`

will not operate in a "meaningful" way:

>>> import Numeric as N >>> a = N.reshape(N.arange(12), (4,3)) >>> a [[ 0, 1, 2,] [ 3, 4, 5,] [ 6, 7, 8,] [ 9,10,11,]] >>> min(a) [0,1,2,] >>> max(a) [ 9,10,11,]

What rules did `min`

and `max`

use to obtain this
result? Konrad Hinsen explains it's the result of an
address comparison! Very odd (at least to an earth scientist).

The `Numeric`

`minimum`

and `maximum`

functions do not use this address comparison method, but rather do
element-wise comparison between two arguments, returning an array of
the same size:

>>> import Numeric as N >>> a = N.array([2, 5, 23, 7,-2]) >>> b = N.array([12, 2, -3,37,-2]) >>> N.minimum(a,b) [ 2, 2,-3, 7,-2,] >>> N.maximum(a,b) [12, 5,23,37,-2,]

However, if you want the min/max of all the elements in a single
array, calling these `Numeric`

functions with a
single argument won't work:

>>> N.minimum(a) Traceback (most recent call last): ... ValueError: invalid number of arguments

The `Numeric`

min/max functions will, however, accept
a single argument array with the `reduce`

attribute,
since `reduce`

effectively considers the sub-array
associated with each position along axis 0 (by default) as an
argument to the function, in pairwise blocks,
and returns the result. Thus:

>>> import Numeric as N >>> c = N.array([[2,4,1,-4], [5,9,-2,4], [2,5,-3,12]]) >>> N.maximum.reduce(c) [ 5, 9, 1,12,]

gives the same result as:

>>> import Numeric as N >>> c1 = N.array([2,4,1,-4]) >>> c2 = N.array([5,9,-2,4]) >>> c3 = N.array([2,5,-3,12]) >>> N.maximum(N.maximum(c1,c2), c3) [ 5, 9, 1,12,]

If you want to get the min/max of all the elements in a single
array, regardless of how many dimensions the array is, one way
is to use the `minimum`

and `maximum`

functions in the `MA`

module. Like their `Numeric`

counterparts, if the functions are called with two arguments an
element-wise comparison is returned. However, in `MA`

the functions can be called with one argument to obtain the overall
min/max:

>>> import MA >>> c = N.array([[2,4,1,-4], [5,9,-2,4], [2,5,-3,12]]) >>> MA.maximum(c) 12