Removing repeated in order elements from array?
9 views (last 30 days)
Show older comments
I have an array like [ 1 1 1 2 2 3 3 3 1 1 1 2 2 4 4 4 5 5 6]
Is there a method which will produce array [ 1 2 3 1 2 4 5 6] and remove all repeating orderly values but not remove all duplicates?
have tried code below with no luck
for k=length(array):-1:1
if array(k)==array(k+1)
array(k)=[]
end
end
0 Comments
Answers (2)
Rik
on 30 Mar 2022
No need for a loop (even if you should have replaced length by numel):
data=[ 1 1 1 2 2 3 3 3 1 1 1 2 2 4 4 4 5 5 6];
L=diff(data)==0; % note: this is 1 element shorter that data itself
data(L)=[]
0 Comments
Voss
on 30 Mar 2022
Your approach will work; you just have to start at the second-to-last element instead of the last:
array = [ 1 1 1 2 2 3 3 3 1 1 1 2 2 4 4 4 5 5 6];
for k=length(array)-1:-1:1
if array(k)==array(k+1)
array(k)=[];
end
end
array
Here's another approach:
array = [ 1 1 1 2 2 3 3 3 1 1 1 2 2 4 4 4 5 5 6];
array(diff(array) == 0) = [];
array
3 Comments
Voss
on 30 Mar 2022
array = [2 2 2 2 2 2 2];
for k=length(array)-1:-1:1
if array(k)==array(k+1)
array(k)=[];
end
end
array
array = [2 2 2 2 2 2 2];
array(diff(array) == 0) = [];
array
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!