Need to remove repeated adjacent elements in an array

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?

3 件のコメント

Michael Cappello
Michael Cappello 2015 年 5 月 15 日
x(diff(x)==0) = []
Matthew Rademacher
Matthew Rademacher 2015 年 5 月 16 日
Thanks!
Ravi Mravi
Ravi Mravi 2017 年 10 月 30 日
Excellent solution

サインインしてコメントする。

 採用された回答

Star Strider
Star Strider 2015 年 5 月 15 日

4 投票

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.

5 件のコメント

Geetha  K
Geetha K 2020 年 4 月 28 日
What if the i/p is like this 1111112233333334555555 And o/p should be 135
Image Analyst
Image Analyst 2020 年 4 月 28 日
How are you getting 135 from that?
Star Strider
Star Strider 2020 年 4 月 28 日
Geetha K —
Your Comment does not relate to this thread. Please post it as a new Question. If you want to cite to this thread, copy the URL and include it in your Question.
Juan Sierra
Juan Sierra 2020 年 11 月 21 日
I'd refine this as
A = [1 1 1 1 2 2 2 6 6 6 6 2 2 2 2];
B = A(diff([A(1)-1, A]) ~= 0)
just in case the first value is 0. Just a small suggestion ;)
Bruno Luong
Bruno Luong 2020 年 11 月 21 日
編集済み: Bruno Luong 2020 年 11 月 21 日
No it's still flawed
>> A=1e20
A =
1.0000e+20
>> B = A(diff([A(1)-1, A]) ~= 0)
B =
[]
>> A=uint8(0)
A =
uint8
0
>> B = A(diff([A(1)-1, A]) ~= 0)
B =
0×0 empty uint8 matrix
Better
B = A([true diff(A)~=0])
Still it does work if A is empty.
The answer by posted by Michael Cappello in the comment is still better.

サインインしてコメントする。

その他の回答 (2 件)

Joseph Cheng
Joseph Cheng 2015 年 5 月 15 日
編集済み: Joseph Cheng 2015 年 5 月 15 日

1 投票

you can use diff to determine the consecutive same value numbers
test = [1 1 1 1 2 2 2 6 6 6 6 2 2 2 2]
mtest = [test test(end)-1];
difftest = diff(mtest)
output = test(difftest~=0)
the mtest is the modified test number to get the last value not the same. if you look at the output of difftest you see that we get the positions of the transitions from one number to another.
Image Analyst
Image Analyst 2015 年 5 月 15 日

0 投票

Here's one way:
m = [1 1 1 1 2 2 2 6 6 6 6 2 2 2 2]
logicalIndexes = [0, diff(m)] ~= 0
output = [m(1), m(logicalIndexes)]

カテゴリ

ヘルプ センター および File ExchangeProgramming についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by