delete zero rows only with one number

2 Ansichten (letzte 30 Tage)
Mahsa
Mahsa am 18 Sep. 2014
Kommentiert: José-Luis am 18 Sep. 2014
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,

Akzeptierte Antwort

Mohammad Abouali
Mohammad Abouali am 18 Sep. 2014
Bearbeitet: Mohammad Abouali am 18 Sep. 2014
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.

Weitere Antworten (3)

José-Luis
José-Luis am 18 Sep. 2014
Bearbeitet: José-Luis am 18 Sep. 2014
your_mat = A(all(A(:,2:end),2),:)

Adam
Adam am 18 Sep. 2014
B = A( sum(A(:,2:end),2) > 0,: )
  2 Kommentare
José-Luis
José-Luis am 18 Sep. 2014
That might not work if there are negative values.
Adam
Adam am 18 Sep. 2014
true!

Melden Sie sich an, um zu kommentieren.


Mahsa
Mahsa am 18 Sep. 2014
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

Community Treasure Hunt

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

Start Hunting!

Translated by