File Exchange

image thumbnail

Max and Min of n-dimensional Matrices

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

1 Download

Updated 08 Jan 2014

View Version History

View License

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)

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

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

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 (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (4)

Jos (10584)

Two useful three-liners.


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

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


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

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!