Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find highest/lowest value in matrix

Tags:

matlab

very basic question: How can I find the highest or lowest value in a random matrix. I know there is a possibility to say:

a = find(A>0.5)

but what I'm looking for would be more like this:

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
like image 537
kojikurac Avatar asked Dec 01 '22 01:12

kojikurac


1 Answers

Have a 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 for now, so even though A is 5x5, it returns the linear index 7.

If you need the 2D coordinates, i.e. the "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 the entries' indices which reach the minimum value, you can use find:

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

I is now a vector of all of them.

like image 110
Jonas Heidelberg Avatar answered Dec 06 '22 21:12

Jonas Heidelberg