2

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?

Dan
  • 45,079
  • 17
  • 88
  • 157
space_voyager
  • 1,984
  • 3
  • 20
  • 31

1 Answers1

4

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
Community
  • 1
  • 1
Benoit_11
  • 13,905
  • 2
  • 24
  • 35
  • Looks great, I'd like to ask though is there any particular reason to use -1 when you append `a(1)-1`? I understand that it is to allow the recording of the first element. – space_voyager Sep 03 '15 at 20:59
  • 3
    There's nothing special about -1. It's just needs to be any value that is NOT `a(1)` to cause diff to find it. – surgical_tubing Sep 03 '15 at 21:36