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

2 次查看(过去 30 天)
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.

采纳的回答

KSSV
KSSV 2020-10-29
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 个评论
Image Analyst
Image Analyst 2020-10-29
编辑:Image Analyst 2020-10-29
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 2020-10-29
@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.

请先登录,再进行评论。

更多回答(1 个)

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

类别

Help CenterFile Exchange 中查找有关 MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by