Borrar filtros
Borrar filtros

Need to erease all the rows of a matrix where a zero appears

2 visualizaciones (últimos 30 días)
Good evening folks (at least, here in Italy it's going to get dark very soon).
I need once more your help with a matrix manipulation. Let the matrix be:
A =
0 0 0
0 0 0
1 1 0
1 1 1
0 0 0
0 1 0
0 0 1
I need to erease all the rows where a null element appears. I.e., I want all the rows to go away minus the "1 1 1" row, so I just want one to survive. Notice that this is an hypothetical matrix, in reality, in my script, I don't know how many lines will be completely filled with ones and I want all of them to survive.
Thanks in advance.

Respuesta aceptada

KSSV
KSSV el 29 de Oct. de 2020
A = [0 0 0
0 0 0
1 1 0
1 1 1
0 0 0
0 1 0
0 0 1] ;
idx = all(A,2) ;
A = A(idx,:)
A = 1×3
1 1 1
  3 comentarios
Image Analyst
Image Analyst el 29 de Oct. de 2020
Editada: Image Analyst el 29 de Oct. de 2020
Not dumb really - perfectly understandable misunderstanding that people make all the time. This is a perfect example of why one of my two main directives I give to people who code for me is to use descriptive variable names, even if they're longer, like indexes instead of idx. (The other one is to use tons of comments.) Below is how I was going to answer your question, before I saw you already got two other answers:
A = [0 0 0
0 0 0
1 1 0
1 1 1
0 0 0
0 1 0
0 0 1] ;
% Find rows that have any non-zero values in them.
rowsWithNonZeros = any(A, 2)
% Extract only those rows with at least one non-zero value in them.
A = A(rowsWithNonZeros, :)
I think this is less cryptic and more understandable and readable (even though it's longer), don't you agree?
Marco Boesso
Marco Boesso el 29 de Oct. de 2020
@KKSV sorry for my delay. Studied and implemented your solution, was brilliant! Thanks, you saved me from problems!
I did not know about this function.

Iniciar sesión para comentar.

Más respuestas (1)

Ameer Hamza
Ameer Hamza el 29 de Oct. de 2020
idx = any(A==0, 2);
A(idx, :) = []

Categorías

Más información sobre MATLAB 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