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

2019-08-03 03:11发布

问题:

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

回答1:

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)


标签: matlab min