finding all indices of a value in matrix

조회 수: 235 (최근 30일)
sambhav jain
sambhav jain 2020년 2월 18일
댓글: sambhav jain 2020년 2월 18일
i have a matrix say
[2 2 3 ;
2 4 2;
2 3 2]
how do i find all the indices (row, column) of 2 (minimum value element of matrix) in the given matrix?
  댓글 수: 4
Stephen23
Stephen23 2020년 2월 18일
"but could you plz tell how is it better by not using find?"
It isn't better, it just demonstrates that every problem can be approached in different ways, and hopefully shows a different way to think about the problem.
sambhav jain
sambhav jain 2020년 2월 18일
ok.thanks again

댓글을 달려면 로그인하십시오.

채택된 답변

Rafael Hernandez-Walls
Rafael Hernandez-Walls 2020년 2월 18일
A=[2 2 3 ;
2 4 2;
2 3 2];
[r,c]=find(A==min(A))
  댓글 수: 2
Stephen23
Stephen23 2020년 2월 18일
편집: Stephen23 2020년 2월 18일
min(A)
should be
min(A(:))
otherwise this code will fail for any matrix which does not contain the minimum value in each column.
sambhav jain
sambhav jain 2020년 2월 18일
thanks a lot sir

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Steven Lord
Steven Lord 2020년 2월 18일
Do you need the locations or do you simply need to refer to the locations where the specified value occurs? Those are two slightly different things. If the latter, you don't need to use find and don't need to compute the indices at all.
Use logical indexing.
A = [2 2 3 ; 2 4 2; 2 3 2]
B = A; % Make a copy of A for future reference
two = A == 2 % Create a logical mask
B(two) = -1 % Replace all 2's in (the copy of) A with -1
In this example, I don't care where the 2's were in A. I only cared that I could change those elements.
  댓글 수: 4
sambhav jain
sambhav jain 2020년 2월 18일
Ok
sambhav jain
sambhav jain 2020년 2월 18일
I first found the minimum value in the matrix and then found the indices of the value using above as given by rafael but yours works too. Thank you

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by