Borrar filtros
Borrar filtros

Find the index of specific values in my matrix

2 visualizaciones (últimos 30 días)
Pouyan Sadeghian
Pouyan Sadeghian el 23 de Jun. de 2021
Comentada: Pouyan Sadeghian el 23 de Jun. de 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

Respuesta aceptada

Scott MacKenzie
Scott MacKenzie el 23 de Jun. de 2021
Editada: Scott MacKenzie el 23 de Jun. de 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
  1 comentario
Pouyan Sadeghian
Pouyan Sadeghian el 23 de Jun. de 2021
Hi Scott,
thanks for your answer. I did not know this command. Very useful.
Thanks!
best

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by