It is often the case where one must find the overall minimum or maximum element of an array, along with the location of that element. This is a flaw of both find and min (or max), that they only work in one dimension.
Most solutions will have you convert the array to a vector, then find the min/max element, and convert the linear index back to row and column subscripts. While this does work on most problems, it will fail for REALLY huge arrays where the linear index is simply too large to fit into a 32 bit integer. The acknowledged file is one such example of a solution that internally converts the matrix to a vector for processing.
MIN2 and MAX2 do not do the conversion to a single linear index, so they have no problems here.
M = magic(4)
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
[minel,IJ] = min2(M)
[maxel,IJ] = max2(M)
MIN2 and MAX2 also allow the user to restrict the search space, so if you wish to find the minimum over some subset of the rows and columns, but not look in the other rows and columns, we can do that too.
[minel,IJ] = min2(M,,[1 2 3])
[maxel,IJ] = max2(M,[2 3 4],[1 2 3])
When the minimal value is not unique, MIN2 and MAX2 will still find the same solution that find would have found, for consistency. MIN2 and MAX2 will also properly handle arrays that have inf or -inf elements in them, and ignore NaN elements in the search.
M2 = M + M';
M2(2,3) = inf;
M2(2,4) = nan
32 7 12 17
7 22 Inf NaN
12 17 12 27
17 22 27 2
[minel,IJ] = min2(M2,1:3,1:3)
[maxel,IJ] = max2(M2)
John D'Errico (2022). MIN2, MAX2 (https://www.mathworks.com/matlabcentral/fileexchange/22995-min2-max2), MATLAB Central File Exchange. Retrieved .
MATLAB Release Compatibility
Platform CompatibilityWindows macOS Linux
Inspired by: Maximum Or Minimum for N Dimension Array
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!