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

隐身守侯 提交于 2019-12-13 02:59:59

问题


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)


来源:https://stackoverflow.com/questions/35996953/matlab-how-to-get-min-value-and-its-index-in-a-matrix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!