Find the index of specific values in my matrix

조회 수: 7 (최근 30일)
Pouyan Sadeghian
Pouyan Sadeghian 2021년 6월 23일
댓글: Pouyan Sadeghian 2021년 6월 23일
Hi,
I have a matrix with zeros and ones and I want to find the index of every one in my matrix and give the index in two vectors. One vector for the x-index and one for the y-index.
This is my matrix:
A = [0 0 1 0 1 0
1 0 1 0 0 1
1 0 1 0 1 0]
size is 3x6
Then I need a vector where the x-position all ones in the matrix is given and another vector where the y-position of all ones in the matrix is given.
I used the find command for my issue but it gives me just the first 1 or the last 1.
And I also tried to wirte a loop:
row=[];
col=[];
for x=1:3
for x=1:6
if A(x,:)==1;
row(y)=x;
col(y)=y;
end
end
end
But without success.
I need these two vectors because I want to plot the matrix.
And the way I think to do it is with the command plot. For that I need the vector with the indexes.
plot(row,col
I hope you understand my issue and can give me a hinte.
Thanks
Best Pouyan

채택된 답변

Scott MacKenzie
Scott MacKenzie 2021년 6월 23일
편집: Scott MacKenzie 2021년 6월 23일
No need for loops. Just use the ind2sub function:
A = [0 0 1 0 1 0
1 0 1 0 0 1
1 0 1 0 1 0]
[x, y] = ind2sub(size(A), find(A==1))
Output:
A =
0 0 1 0 1 0
1 0 1 0 0 1
1 0 1 0 1 0
x =
2
3
1
2
3
1
3
2
y =
1
1
3
3
3
5
5
6
  댓글 수: 1
Pouyan Sadeghian
Pouyan Sadeghian 2021년 6월 23일
Hi Scott,
thanks for your answer. I did not know this command. Very useful.
Thanks!
best

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

추가 답변 (0개)

카테고리

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