File Exchange

## Max and Min of n-dimensional Matrices

version 1.1.0.0 (2.03 KB) by
Determines the max / min value and its index position of an n-dimensional matrix

Updated 08 Jan 2014

Determines the minimum / maximum value and its index of an n-dimensional
matrix. E.g., for a 2D-Matrix x and y position of the min / max value are
returned, for a 3D-Matrix x, y and z position of min / max value are returned.

Syntax: [v,idx] = minN(A) / [v,idx] = minN(A)

Inputs:
A - the matrix of which the minimum / maximum value shall be found

Outputs:
v - the minimum / maximum value of A
idx - the index of v in matrix A

Example:
A(:,:,1) = [1,1,2;1,1,1;1,1,1];
A(:,:,2) = [1,1,1;1,1,1;1,1,1];
A(:,:,3) = [1,1,1;1,1,1;0,1,1];

[v1,idx1] = minN(A);
[v2,idx2] = maxN(A);

% v1 = 0, and idx1 = [3,1,3]
% v2 = 2, and idx2 = [1,3,1]
% it is A(3,1,3) = 0
% it is A(1,3,1) = 2

### Cite As

Christopher (2021). Max and Min of n-dimensional Matrices (https://www.mathworks.com/matlabcentral/fileexchange/44758-max-and-min-of-n-dimensional-matrices), MATLAB Central File Exchange. Retrieved .

Jos (10584)

Two useful three-liners.

Christopher

@Jos: Thanks for the significant improvement!

I've updated the files according to your suggestions. Will keep the files online for now as they were downloaded a few times, even though it is just a 3-liner now.

Jos (10584)

@Christopher, you know n:

[MaxValue, LinearIndex] = max(A(:))
[SubIndex{1:ndims(A)}] = ind2sub(size(A),LinearIndex)
A(SubIndex{:})

In most cases, linear indexing suffices to retrieve a value from an array.

Christopher

Does essentially the same as the two lines:

>> [v,idx]=max(A(:))
>> [x1,x2,...,xn]=ind2sub(size(A),idx)

with the benefit that the number of dimensions x1,...,xn does not need to be known prior to the computation.

I use the idx vector as follows to access a certain matrix element:

>> idxCell = num2cell(idx);
>> myEl = A(idxCell{:});

##### MATLAB Release Compatibility
Created with R2012a
Compatible with any release
##### Platform Compatibility
Windows macOS Linux