Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get MATLAB to display the index of the minimum value in a 2D array?

Tags:

matlab

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.

like image 775
Mike C Avatar asked Feb 22 '11 10:02

Mike C


People also ask

How do you find the minimum value of a 2d matrix in MATLAB?

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.

How do you find the index of a value in an array in MATLAB?

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.

How do you find the index of a maximum value in MATLAB?

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

How do you find the minimum and maximum value in MATLAB?

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 .


2 Answers

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)));
like image 103
Adrian Avatar answered Sep 23 '22 21:09

Adrian


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
like image 21
b3. Avatar answered Sep 21 '22 21:09

b3.