Mathematica Programming Tips & Tricks Collection, Biomedical Imaging, TU/e

Subject of the Trick

Fast Max and Min Position

Author

Markus van Almsick

Keywords (List of Strings)

Abstract

The Mathematica command Ordering can find the position of a maximum or minimum in an n-dimensional data array faster than using Max or Min in Position.

Implementation

Code

Explanation (Optional)

Up front we install the utility function PartitionInteger that converts the position pos in a flattened array back to the coordinates in the nested array with the dimensions dims. Example:

Ordering[data,1] renders the position of the first element in the sorted data list, hence the position of a or the minimum. Ordering[data,-1] returns the position of the last element in the sorted data list, which is a or the maximum. To extend this command to n-dimensional arrays, we simply flatten these arrays and recalculate the coordinates from the linear position.

Example

Creating an array of random numbers between 0 and 1.

Inserting a maximum.

Testing our implementation.

Comparing the result with a more conventional code.

Comparing the execution speed:

Note the speed gain by a factor of 25!

Created by Mathematica (October 24, 2003)