Delete duplicates - ** only when duplicates are repeated

I would like to do something similar to the following, except that I would like to remove "g" and "g", because these are duplicates that occur one after another. I would also like to keep the sequence the same.

Any help would be appreciated.

I have this array of cells in MATLAB:

y = { 'd' 'f' 'a' 'g' 'g' 'w' 'a' 'h'}


ans =

'd'    'f'    'a'    'w'    'a'    'h'
+3
source share
3 answers

In my first answer (below), an error occurred while using multiple duplicates (thanks grantnz). Here's the updated version:

>> y = {'d' 'f' 'a' 'g' 'g' 'w' 'a' 'h' 'h' 'i' 'i' 'j'};
>> i = find (diff (char (y)) == 0);
>> y([i; i+1]) = []

y = 

    'd'    'f'    'a'    'w'    'a'    'j'

OLD ANSWER

" " , :

>> y = { 'd' 'f' 'a' 'g' 'g' 'w' 'a' 'h'}

y = 

    'd'    'f'    'a'    'g'    'g'    'w'    'a'    'h'

>> y(find(diff(char(y)) == 0) + [0 1]) = []

y = 

    'd'    'f'    'a'    'w'    'a'    'h'
+3

: , (1) (2) , (3) , (4) . :

y([true ~strcmp(y(1:(end-1)),y(2:end))] & [~strcmp(y(1:(end-1)),y(2:end)) true])

, , ,

different = ~strcmp(y(1:(end-1)),y(2:end));
result = y([true different] & [different true]);
+1

:

 y([ diff([y{:}]) ~= 0 true])

or a little more compact

 y(diff([y{:}]) == 0) = []

Fix: the above will not remove both duplicates

ind = diff([y{:}]) == 0;
y([ind 0] | [0 ind]) = []

BTW, this works even if there are multiple repeating sequences

eg,

y = { 'd' 'f' 'a' 'g' 'g' 'w' 'a' 'h' 'h'};
ind = diff([y{:}]) == 0;

y([ind 0] | [0 ind]) = []

y = 

     'd'    'f'    'a'    'w'    'a'
0
source

All Articles