How to find maximal entry in a Numpy array?
alex
alex at somewhere.around.here
Sat May 1 23:20:59 EDT 1999
Hi. Is there a fast way to find the location of a maximal entry in a
Numeric array? I realize I could do something along the lines of
flattening it, finding the maximum value, and then searching for that
value, but that means going over the array twice. I could also use
argmax to find the position of the largest value in each column, make a
new array with dimension one less containing those maximal values, and
repeat, but I can't see how to make that new array without doing a
slow-looking python loop.
The best I've been able to come up with is to search in a python loop
over the entries specified by argmax. Is there a way to push more of
this down into C loops? And can someone please show me something better
than this horrendous "else: break" trick for iterating over the tuples
with entries less than some specific tuple?
import copy, Numeric
def find_max (array):
maximal_indices = argmax (array)
ashape = maximal_indices.shape
index = len (ashape) * [0]
maximal_value = 0
while 1:
if array [index + [maximal_indices [index]]] > \
maximal_value:
maximal_value = array [ \
index + [maximal_indices [index]]]
maximal_index = copy.copy (index)
for i in range (len (index)):
index [i] = index [i] + 1
if index [i] < ashape [i]: break
index [i] = 0
else: break
return maximal_index + [maximal_indices [index]]
In the end, I'm probably not going to be happy with just the maximal
value, either. If there's a fast way to get all the indices, sorted by
their values, that would be even better.
No-harm-in-asking'ly Alex.
More information about the Python-list
mailing list