Need to remove repeated adjacent elements in an array
13 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Matthew Rademacher
el 15 de Mayo de 2015
Editada: Bruno Luong
el 21 de Nov. de 2020
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 comentarios
Respuesta aceptada
Star Strider
el 15 de Mayo de 2015
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 comentarios
Juan Sierra
el 21 de Nov. de 2020
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
el 21 de Nov. de 2020
Editada: Bruno Luong
el 21 de Nov. de 2020
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.
Más respuestas (2)
Joseph Cheng
el 15 de Mayo de 2015
Editada: Joseph Cheng
el 15 de Mayo de 2015
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.
0 comentarios
Image Analyst
el 15 de Mayo de 2015
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)]
0 comentarios
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!