I'm trying to write a script in MATLAB that finds the location of the minimum value of a 2D array of numbers. I am certain there is only 1 minimum in this array, so having multiple locations in the array with the same minimum value is not an issue. I can find the minimum value of the array, but in a 30x30 array, I would like to know which row and column that minimum value is in.
M = min( A ,[], dim ) returns the minimum element along dimension dim . For example, if A is a matrix, then min(A,[],2) is a column vector containing the minimum value of each row.
In MATLAB the array indexing starts from 1. To find the index of the element in the array, you can use the find() function. Using the find() function you can find the indices and the element from the array. The find() function returns a vector containing the data.
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. Here, 7 is the largest number at the 4th position(index).
minA is equivalent to min(A) and maxA is equivalent to max(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 .
As an alternative version, combine min to get the minimum value and find to return the index, if you've already calculated the minimum then just use find.
>> a=magic(30);
>> [r,c]=find(a==min(min(a)))
r =
1
c =
8
Or depending on how you want to use the location information you may want to define it with a logical array instead, in which case logical addressing can be used to give you a truth table.
>> a=magic(30);
>> locn=(a==min(min(a)));
You could reshape the matrix to a vector, find the index of the minimum using MIN and then convert this linear index into a matrix index:
>> x = randi(5, 5) x = 5 4 4 2 4 4 2 4 5 5 3 1 3 4 3 3 4 2 5 1 2 4 5 3 5 >> [value, index] = min(reshape(x, numel(x), 1)); >> [i,j] = ind2sub(size(x), index) i = 3 j = 2
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