# How do I find all local minima in a multidimensional array?

I'd like to find all local minima in an array of data. The array I'm working with is 3D, but I'll use a 2D example to illustrate what I mean:

Say I have the following array:

data={{5,6,7,4,9},{8,6,4,2,7},{6,7,5,2,4},{1,8,9,9,5},{6,1,2,7,4}};


The local minima occur at (1,1), (2,4), (3,4), (4,1), (5,2) and (5,5). If I were to use

Position[data,Min[Min[data]]]


I would get {{4,1}} because the global minimum of the data occurs at (4,1); the other three local minima would be lost. How can I obtain them? This question concerns 1-dimensional data, and this solution isn't working for me (it returns the error Last::nolast: {} has zero length and no last element. >> and an empty set).

If you need a MWE, just use data=RandomReal[{0,1},{11,21,31}];.

You can use MinDetect:

data // MatrixForm // TeXForm


$$\left( \begin{array}{ccccc} 5 & 6 & 7 & 4 & 9 \\ 8 & 6 & 4 & 2 & 7 \\ 6 & 7 & 5 & 2 & 4 \\ 1 & 8 & 9 & 9 & 5 \\ 6 & 1 & 2 & 7 & 4 \\ \end{array} \right)$$

MinDetect[data] // MatrixForm // TeXForm


$$\left( \begin{array}{ccccc} 1 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 1 & 0 \\ 1 & 0 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 & 1 \\ \end{array} \right)$$

Position[MinDetect[data], 1]


{{1, 1}, {2, 4}, {3, 4}, {4, 1}, {5, 2}, {5, 5}}

MinDetect[data] data // MatrixForm // TeXForm


$$\left( \begin{array}{ccccc} 5 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 2 & 0 \\ 0 & 0 & 0 & 2 & 0 \\ 1 & 0 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 & 4 \\ \end{array} \right)$$

• Well, that was surprisingly simple. Thanks!
– Rain
Oct 4 '18 at 22:04
• @Rain, my pleasure.
– kglr
Oct 4 '18 at 22:07