1
votes

I have a matrix with 2 columns. I would like to delete rows based on a sequence of numbers in column 2. For example:

Data = [1 2
        3 4
        5 4
        6 2
        7 0
        8 2]

then delete rows if sequence in column 2 is 4 4 2. so I would end up with:

Data = [1 2
        7 0
        8 2]
2

2 Answers

1
votes

Let's add some data to Data, to show this on two [4 4 2] sequences:

Data =

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

Now, this should do the job and delete the rows that include the sequence [4 4 2] in the second column:

Seq=[4 4 2];       % sequence to delete rows according to
Data(bsxfun(@plus,findstr(Data(:,2)',Seq)',(0:length(Seq)-1)),:)=[]

Data =

     1     2
     7     0
     8     2
     9     2
     4     0
     3     2
0
votes

Answer provided by @Adiel is greate, however if the range of numbers contained in Data is beyond the values that can be represented by character strings you can use this method:

Data = [1 2
        3 4
        5 4
        6 2
        7 0
        8 2]
Seq = [4 4 2]

Create a matrix that shows equality of Seq with elements of Data:

r = size(Data, 1);
n = numel(Seq);
idx = bsxfun(@eq, Data(:,2), Seq);
idx =

   0   0   1
   1   1   0
   1   1   0
   0   0   1
   0   0   0
   0   0   1

We then should reshape idx to size [r+1,n]:

idx2 = false(r+1, n);
idx2(idx) = true;
idx2 =

   0   1   0
   1   1   1
   1   0   0
   0   0   1
   0   0   0
   0   1   0
   0   0   0

Now if a sequence of [4 4 2] is contained in Data all elements of each row of idx2 will be 1. So we should find such rows.

    f = find(all(idx2, 2));
    f = 

       2

So indexes of beginning of each sequence is found . To find other elements we add 0:n-1 to f .

idx3 = bsxfun(@plus, f, 0:n-1);
idx3 =

   2   3   4

Remove elements:

Data(idx3, :) = [];
Data =

   1   2
   7   0
   8   2