Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Removing zero rows from a matrix

  1. Aug 8, 2011 #1
    say,

    Code (Text):
    a = [1,2,3; 0,0,0; 0,4,5];
    how can I remove the rows of a that contain only zeros?

    I found a link which works, but I don't know why:
    http://www.mathworks.in/matlabcentral/newsreader/view_thread/281578
    Suggesting:
    Code (Text):
    a(all(a==0,2),:)=[]
    1. what does the "=[]" syntax do
    2. can this method be used to generate a second matrix b = a(without any zero rows)? I tried re-writing in this form and it doesn't work:

    Code (Text):
    >> b = a(all(a==0,2),:)
    b =
         0     0     0
    Clearly I'm missing something,
    Thanks
     
  2. jcsd
  3. Aug 8, 2011 #2

    uart

    User Avatar
    Science Advisor

    If you want something that's a bit less cryptic and a bit more transparent you could do it like this

    Code (Text):

    k=0; rows=size(a)(1)
    while (k<rows)
       k=k+1;
       if all(a(k,:)==0)
          a(k,:)=[];
          rows=rows-1;
       end
    end
     
    Note that you can't use a "for" loop because if a row is removed then it will reduce the size of the matrix, causing the for loop index to eventually exceed the size of the matrix. This problem of course only arises because you're processing the matrix "in place".

    BTW, [] just represents an empty vector.
     
    Last edited: Aug 8, 2011
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook