[Tutor] array
Alex Cobb
acobb@oeb.harvard.edu
Sun, 17 Mar 2002 23:35:28 -0500
Hi there,
I'm hardly a Numeric wiz but I've been using this:
>>> import Numeric
>>> M = Numeric.arange(0, 25) ## creates a 1-D example array of
values 0 to 24
>>> M = Numeric.reshape(M, (5,5)) ## makes this into a
square 2-D matrix
>>> M
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
>>> max = Numeric.maximum.reduce(M.flat)
>>> max
24
I don't know how this compares in terms of speed to the solution
below (" max([max(row) for row in M]) "), but it's a pretty
convenient if you're already using NumPy.
Hope this helps
Alex
At 08:58 PM 3/17/2002 -0700, Paul Sidorsky wrote:
>Karshi wrote:
>
> > How do find the maximum number in an array: say A[i,j] ?
> > I've got the following error when I tried to use "max":
> > --------------------------------------------------------------------
> > >>> M=array([[1,2,3,],[3,4,56],[4,6,8]], Float32)
> > >>> M
> > array([[ 1., 2., 3.],
> > [ 3., 4., 56.],
> > [ 4., 6., 8.]],'f')
> > >>> max(M)
> > array([ 4., 6., 8.],'f')
> > ---------------------------------------------------------------------
> > which is not true.
>
>Actually it is true. Python does a memberwise comparison of sequence
>types, and 4>3>1 so the last row is the biggest according to Python's
>comparison logic.
>
>Anyhow, try this:
>
> >>> max([max(row) for row in M])
>56.0
>
>This pulls the maximum out of each row and then takes the maximum of
>those maximums.
>
>I don't know if there's a faster solution using NumPy itself, but at
>least this is something that seems to work.
>
>--
>======================================================================
>Paul Sidorsky Calgary, Canada
>paulsid@shaw.ca http://members.shaw.ca/paulsid/
>
>_______________________________________________
>Tutor maillist - Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor