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

1 view (last 30 days)
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.

Accepted Answer

KSSV
KSSV on 29 Oct 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 Comments
Image Analyst
Image Analyst on 29 Oct 2020
Edited: Image Analyst on 29 Oct 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 on 29 Oct 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.

Sign in to comment.

More Answers (1)

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

Categories

Find more on MATLAB in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!