[Numpy-discussion] flatindex

Stefan van der Walt stefan at sun.ac.za
Fri Jun 1 11:29:54 EDT 2007

Hi Tobias

On Thu, Jan 08, 2004 at 08:35:07PM +0100, Tobias Knopp wrote:

Sorry I'm only answering now, but your mail took 3.5 years to arrive ;)

> I was looking for a method to find the indices of the smallest element
> of an 3-dimensional array a. Therefore i used
> a.argmax()
> The problem was, that argmax gives me a flat index. My question is, if
> there is a build-in function to convert the flat index back to a
> multidimensional one. I know how to write such a procedure but was
> curious if one exists in numpy.


    Convert a flat index into an index tuple for an array of given shape.
    e.g. for a 2x2 array, unravel_index(2,(2,2)) returns (1,0).
    Example usage:
      p = x.argmax()
      idx = unravel_index(p,x.shape)
      x[idx] == x.max()
    Note:  x.flat[p] == x.max()
      Thus, it may be easier to use flattened indexing than to re-map
      the index to a tuple.


More information about the NumPy-Discussion mailing list