I have a 4D array of measurements in MATLAB. Each dimension represents a different parameter for the measurement. I want to find the maximum and minimum value and the index (i.e. which parameter) of each.
What's the best way to do it? I figure I can take the max of the max of the max in each dimension, but that seems like a kludge.
M = max( A ) returns the maximum elements of an array. If A is a vector, then max(A) returns the maximum of A . If A is a matrix, then max(A) is a row vector containing the maximum value of each column of A .
[ minA , maxA ] = bounds( A , 'all' ) computes the minimum and maximum values over all elements of A . This syntax is valid for MATLAB® versions R2018b and later. [ minA , maxA ] = bounds( A , dim ) operates along the dimension dim of A .
We find maximum and minimum of matrix separately using linear search. Number of comparison needed is n2 for finding minimum and n2 for finding the maximum element. The total comparison is equal to 2n2. Pair Comparison (Efficient method):
You can use max() to get the max value. The max function can also return the index of the maximum value in the vector. To get this, assign the result of the call to max to a two element vector instead of just a single variable.
Quick example:
%# random 4 d array with different size in each dim
A = rand([3,3,3,5]);
%# finds the max of A and its position, when A is viewed as a 1D array
[max_val, position] = max(A(:));
%#transform the index in the 1D view to 4 indices, given the size of A
[i,j,k,l] = ind2sub(size(A),position);
Finding the minimum is left as an exercise :).
Following a comment:
If you do not know the number of dimensions of your array A and cannot therefore write the "[i,j,k,l] =
" part, use this trick:
indices = cell(1,length(size(A)));
[indices{:}] = ind2sub(size(A),position);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With