简体   繁体   中英

matlab how to get min value and its index in a matrix

I have a matrix let's say like this

A=[1 3 6 2 0 4
   6 8 9 5 1 4
   7 2 7 8 9 2]

I want to get the minimal value where the row is given ( r ) and the column is in an interval ( [c.. c+x] ). Also I want the index (number of column of it). I can get the min with

MinVal=min(A(r,c:c+x))

Example

MinVal=min(A(2,3:3+2))

will give me

 % MinVal= 1

The index of this MinVal is I= 5 since it is in the 5th column (I know already the row and don't need it).

But how to get this index ?

If I do like this, I don't get what I want

 [MinVal,I]=min(A(r,c:c+x))

It might not be the shortest code, but an easy to understand possibility:

Create a mask indicating which variables you use in your submatrix:

 M=false(size(A));
 M(r,c:c+x)=true; %use the same indexing operation

Convert to linear indices:

M=find(M);

And use it to translate I to indices in the full matrix:

M(I)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM