Search code examples
matlabvectorduplicatesunique

Delete adjacent repeated terms


I have the following vector a:

a=[8,8,9,9,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8]

From a I want to delete all "adjacent" repetitions to obtain:

b=[8,9,1,2,3,4,5,6,7,8]

However, when I do:

unique(a,'stable')

ans =

     8     9     1     2     3     4     5     6     7

You see, unique only really gets the unique elements of a, whereas what I want is to delete the "duplicates"... How do I do this?


Solution

  • It looks like a run-length-encoding problem (check here). You can modify Mohsen's solution to get the desired output. (i.e. I claim no credit for this code, yet the question is not a duplicate in my opinion).

    Here is the code:

    a =[8,8,9,9,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8]
    
    F=find(diff([a(1)-1, a]));
    

    Since diff(a) returns an array of length (length(a) -1), we want to add a value at the beginning (i.e the a(1)) to get a vector the same size as a. Here we subtract 1 so that, as mentioned by @surgical_tubing, the command find effectively finds it because it looks for non zero elements, so we want to make sure the value is non zero.

    Hence diff([a(1)-1, a]) looks like this:

      Columns 1 through 8
    
         1     0     1     0    -8     0     1     0
    
      Columns 9 through 16
    
         1     0     1     0     1     0     1     0
    
      Columns 17 through 20
    
         1     0     1     0
    

    Now having found the repeated elements, we index back into a with the positions found by find:

    newa=a(F)
    

    and output:

    newa =
    
      Columns 1 through 8
    
         8     9     1     2     3     4     5     6
    
      Columns 9 through 10
    
         7     8