필터 지우기
필터 지우기

How to find the position of the elements of a matrix?

조회 수: 101 (최근 30일)
giorgos kazas
giorgos kazas 2020년 2월 3일
답변: giorgos kazas 2020년 2월 4일
I have a 3x3 matrix: J=[0 3 4;3 0 8;4 8 0]
and I want to know in which position the elements exist. For example that 8 exists in second row and third column (2,3) and (3,2) too.
After that I want a new matrix with the value (i.e. 8) in one column and their ''coordinates'' (i.e. 2,3) in a column side by side.
Thanks
  댓글 수: 2
Steven Lord
Steven Lord 2020년 2월 3일
Paul Shoemaker's answer will give you the indices of the selected elements in the array, but depending on what you want to do that may not be necessary. For example if you want to get the elements of another array (the same size as J) in the same location as the 8's in J you can do this using logical indexing.
J=[0 3 4;3 0 8;4 8 0]
M = magic(3)
X = M(J == 8)
The vector X contains 9 and 7, the elements from M in locations corresponding to 8's in J. See this documentation page for more information.
Paul Shoemaker
Paul Shoemaker 2020년 2월 3일
Yes, Steven Lord makes a good point: usage may drive you a different way. This is why it's helpful for those posting questions to explain what their end objective is, not just how to perform some specific mechanical action.
Similar to Steven's example, you can also change the original "J" variable where a certain condition is met:
J(J==8) = NaN; % efficient way to change all occurrences of "8" in the original matrix to be NaN's
Paul S

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

채택된 답변

Paul Shoemaker
Paul Shoemaker 2020년 2월 3일
Check out the ind2sub Matlab function.
Paul Shoemaker
MatlabInvesting.com
  댓글 수: 4
giorgos kazas
giorgos kazas 2020년 2월 3일
Thank you very much!
Guillaume
Guillaume 2020년 2월 3일
편집: Guillaume 2020년 2월 3일
Hum, this is rather convoluted! For 2D matrices,
[i,j] = ind2sub(size(J),find(J==8));
is simply:
[i, j] = find(J == 8)
For ND matrices, N >= 3, then indeed it makes sense to use ind2sub.

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

추가 답변 (1개)

giorgos kazas
giorgos kazas 2020년 2월 4일
Thank you to everyone for the input.
I have also another question.
Do you know how can I get the results from "disp([i j])" into a matrix? Because I want to create a matrix with the values in one column and their position in the second-third column.

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by