# Find the index of specific values in my matrix

6 views (last 30 days)
Pouyan Sadeghian on 23 Jun 2021
Commented: Pouyan Sadeghian on 23 Jun 2021
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 on 23 Jun 2021
Edited: Scott MacKenzie on 23 Jun 2021
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
Pouyan Sadeghian on 23 Jun 2021
Hi Scott,
thanks for your answer. I did not know this command. Very useful.
Thanks!
best