removing duplicates in an array

57 views (last 30 days)
Esegboria Osarhemen
Esegboria Osarhemen on 3 Mar 2019
Edited: Brent F on 10 Jun 2021
If i have the following array
a =[1,1,1,2,2,1,1,6,6,6,8,8,2,2,3,3,2,2]
When i do unique(a,'stable'), i get
[1,2,6,8,3]
I want the following result
[1,2,1,6,8,2,3,2]

Accepted Answer

Stephan
Stephan on 3 Mar 2019
b = a(logical([1 (diff(a)~=0)]))
  2 Comments
Jan
Jan on 4 Mar 2019
(diff(a)~=0) is a logical vector. Concatenating it with a double converts it to a double. Casting it by logical() converts it again. More efficient:
b = a([true, diff(a)~=0])
Now the values are not converted twice.

Sign in to comment.

More Answers (1)

Brent F
Brent F on 10 Jun 2021
Edited: Brent F on 10 Jun 2021
Using @Jan's idea, but:
  • Package as a function
  • Handle case where column-vector is given (return in same format as given)
function [uniqueSequence] = DedupSequence (seq)
% Eliminate sequentially repeated rows
% Create row vector for diff (must transpose if given a column vector)
if size(seq,1) > 1
seqCopy = seq(:,1)';
else
seqCopy = seq;
end
uniqueSequence = seq([true, diff(seqCopy)~=0]);
end

Categories

Find more on Graphics Object Programming 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!