필터 지우기
필터 지우기

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

조회 수: 1 (최근 30일)
Marco Boesso
Marco Boesso 2020년 10월 29일
댓글: Marco Boesso 2020년 10월 29일
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에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by