# Find the index of specific values in my matrix

조회 수: 2(최근 30일)
댓글: 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 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표시숨기기 없음
Hi Scott,
thanks for your answer. I did not know this command. Very useful.
Thanks!
best

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

### Community Treasure Hunt

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

Start Hunting!

Translated by