Need to erease all the rows of a matrix where a zero appears
조회 수: 1 (최근 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.
댓글 수: 0
채택된 답변
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,:)
댓글 수: 3
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?
추가 답변 (1개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!