MIN2, MAX2

Global min or max value of a 2-d array, the search may be limited to specified rows or columns
3,5K téléchargements
Mise à jour 23 mars 2010

Afficher la licence

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)
M =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1

[minel,IJ] = min2(M)

minel =
1

IJ =
4 4

[maxel,IJ] = max2(M)

maxel =
16

IJ =
1 1

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])

minel =
2

IJ =
1 2

[maxel,IJ] = max2(M,[2 3 4],[1 2 3])

maxel =
15

IJ =
4 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
M2 =
32 7 12 17
7 22 Inf NaN
12 17 12 27
17 22 27 2

[minel,IJ] = min2(M2,1:3,1:3)

minel =
7
IJ =
2 1

[maxel,IJ] = max2(M2)

maxel =
Inf

IJ =
2 3

Citation pour cette source

John D'Errico (2024). MIN2, MAX2 (https://www.mathworks.com/matlabcentral/fileexchange/22995-min2-max2), MATLAB Central File Exchange. Récupéré le .

Compatibilité avec les versions de MATLAB
Créé avec R2007b
Compatible avec toutes les versions
Plateformes compatibles
Windows macOS Linux
Catégories
En savoir plus sur Matrix Indexing dans Help Center et MATLAB Answers
Tags Ajouter des tags
Remerciements

Inspiré par : 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!
Version Publié le Notes de version
1.1.0.0

Repair to the help