MATLAB: Need to remove repeated adjacent elements in an array

diff()repeat values removeunique

I need to turn
[1 1 1 1 2 2 2 6 6 6 6 2 2 2 2] into [1 2 6 2]
unique() gives [1 2 6], but I want to preserve the second value
any advice?

Best Answer

Taking advantage of ‘logical indexing’, it is relatively straightforward:
A = [1 1 1 1 2 2 2 6 6 6 6 2 2 2 2];
B = A(diff([0 A])~=0);
The code looks for changes in the differences (from the diff function) in ‘A’, then finds the elements in ‘A’ that correspond to those changes.