Find the highest / lowest value in the matrix

a very simple question: how can I find the highest or lowest value in a random matrix. I know there is an opportunity to say:

a = find(A>0.5) 

but what I'm looking for will be more like:

 A = rand(5,5) A = 0.9388 0.9498 0.6059 0.7447 0.2835 0.6338 0.0104 0.5179 0.8738 0.0586 0.9297 0.1678 0.9429 0.9641 0.8210 0.0629 0.7553 0.7412 0.9819 0.1795 0.3069 0.8338 0.7011 0.9186 0.0349 % find highest (or lowest) value ans = A(19)%for the highest or A(7) %for the lowest value in this case 
+4
source share
3 answers

Look at the min() and max() functions. They can return both the highest / lowest value and its index:

 [B,I]=min(A(:)); %# note I fixed a bug on this line! 

returns I=7 and B=A(7)=A(2,2) . The expression A(:) tells MATLAB to treat A as a 1D array, so although A is 5x5, it returns a linear index of 7.

If you need 2D coordinates, that is, β€œ2.2” in B=A(7)=A(2,2) , you can use [I,J] = ind2sub(size(A),I) , which returns I=2,J=2 , see here .

Update
If you need all record indices that reach the minimum value, you can use find :

 I = find(A==min(A(:)); 

I now the vector of all of them.

+16
source

For matrices, you need to run MIN and MAX , since they work in columns, i.e. max(A) returns a vector, each element of which is the maximum element in the corresponding column A.

  >> A = rand (4)

 A =

          0.421761282626275 0.655740699156587 0.678735154857773 0.655477890177557
          0.915735525189067 0.0357116785741896 0.757740130578333 0.171186687811562
          0.792207329559554 0.849129305868777 0.743132468124916 0.706046088019609
          0.959492426392903 0.933993247757551 0.392227019534168 0.0318328463774207

 >> max (max (A))

 ans =

          0.959492426392903

 >> min (min (A))

 ans =

         0.0318328463774207

Please note that this only works for matrices. For more massive arrays, MIN and MAX will be required as many times as there are sizes that you can use with NDIMS .

+3
source

try it

 A=magic(5) [x,y]=find(A==max(max(A))) %index maximum of the matrix A A_max=A(x,y) [x1,y1]=find(A==min(max(A))) %index minimum of the matrix A A_min=A(x1,y1) 
0
source

All Articles