Tuesday, March 24, 2015

remove any rows that contains a specific number in Matlab

In this post, I am trying to solve the problem given in the comments of one of the old post.
Here's the problem, if I understand it correctly:

a =

     1     2     3     4     5
     2     3     4   -99     6
     3     4     5     6     7
     4   -99     6     7     8
     5     6     7     8     9

How to remove all the rows that contains the number -99, in this case, the row #2 and #4?

And here's the code I wrote to do this job:

[rows col]=size(a); %count the number of rows and columns of matrix a
j=0; %initialize a counter;
for i=1: rows
    if sum(a(i,:)~=-99)==col; %This determines if the row has -99 or not, if not, do nothing
    else     %shift all of the rest of the rows up one row
        for m=i: rows-1; 
        a(m,:)=a(m+1,:);
        end
        j=j+1; %count how many rows has -99, which equals how many times the rows has been shifted up 
    end
end
b=a((1:rows-j),:); %get rid of the last j rows


The result is:



b =


     1     2     3     4     5
     3     4     5     6     7
     5     6     7     8     9



I hope this can work for you, Winifred. Thanks for your comments!

No comments:

Post a Comment