开发者

Find highest/lowest value in matrix

开发者 https://www.devze.com 2023-04-10 18:34 出处:网络
very basic question: How can I find the highest or lowest value in a random matrix. I know there is a possibility to say开发者_开发问答:

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


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.


For matrices you need to run the MIN and MAX functions twice since they operate column-wise, i.e. max(A) returns a vector with each element being the maximum element in the corresponding column of 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

Note that this only works for matrices. Higher dimensional arrays would require running MIN and MAX as many times as there are dimensions which you can get using NDIMS.


Try this out

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号