delete zero rows only with one number

조회 수: 1 (최근 30일)
Mahsa
Mahsa 2014년 9월 18일
댓글: José-Luis 2014년 9월 18일
Dear all, I have a matrix like A =[23 45 23 56;26 0 0 0;45 23 65 34;34 0 0 0] I want a very efficient way to delete only the rows that has zero value from the second column to the end so the result should be
B = [23 45 23 56;45 23 65 34];
Thank you so much,

채택된 답변

Mohammad Abouali
Mohammad Abouali 2014년 9월 18일
편집: Mohammad Abouali 2014년 9월 18일
This will work
A(~any(A'==0),:)
Don't forget " ' " to transpose A in ~any(A ' ==0).
Alternatively if you want to avoid transpose you can do this:
A(~any(A==0,2),:)
If you want just second column and on then
A(~any(A(:,2:end)'==0),:) or A(~any(A(:,2:end)==0,2),:)
Here is how it works
A(:,2:end)==0 generates a logical the same size as A (except that it has one less column). Any entry of A that are zero that A(:,2:end)==0 would be true the rest would be false. Lets call this C=A(:,2:end)==0
now:
any(A(:,2:end)==0,2) is the same as saying any(C,2). This command searches the rows of C and if there is even one true value (i.e. even of A has one zero value on that row) returns true, otherwise it returns false. Lets have D=any(C,2). D would be another logical variable with the same number of elements as the number of rows in A. if that row of A has any zero number in it it would be true, otherwise it would be false.
now
A(~any(A(:,2:end)==0,2),:) is equal to A(~D,:) pretty much returns all columns of A but only those rows of that do not have any zero in it.
This approach will filters any row of A that have even one zero from column 2 to the last column. If you need to filter all those rows that all elements on column2 to the last column are zero just replace "any" with "all".
If you want to filter rows that have different number just change ==0 to ==n where n is your desired number.

추가 답변 (3개)

José-Luis
José-Luis 2014년 9월 18일
편집: José-Luis 2014년 9월 18일
your_mat = A(all(A(:,2:end),2),:)

Adam
Adam 2014년 9월 18일
B = A( sum(A(:,2:end),2) > 0,: )
  댓글 수: 2
José-Luis
José-Luis 2014년 9월 18일
That might not work if there are negative values.
Adam
Adam 2014년 9월 18일
true!

댓글을 달려면 로그인하십시오.


Mahsa
Mahsa 2014년 9월 18일
if a = [9 0 0; 7 0 0; 8 2 0; 8 8 8] K>> t=a(all(a(:,2:end),2),:)
t =
8 8 8
however it should be
K>> t=a(any(a(:,2:end),2),:)
t =
8 2 0
8 8 8
Thank you Jose, I really appreciate it. I don't know why I can't understand some sequence parenthesis with meaning of if. I mean should I read your code like this: A if all columns of A from 2 to end are exist? Thank you
  댓글 수: 1
José-Luis
José-Luis 2014년 9월 18일
It should be all(), not any()

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by