Remove duplicates from array, some first and some last

6 views (last 30 days)
Hi -- I would like to remove duplicate entries from this array, but sometimes keep the first occurance and sometimes the last.
A = [1 0;
2 0;
3 1;
4 2;
5 3;
6 3;
7 3];
I want to identify duplicates in the second column. At the beginning of the array, I would like to keep the last duplicate and at the end, I would like to keep the first, so my output would be:
ans = [2 0;
3 1;
4 2;
5 3];
I am familiar with, e.g.,
[C,ia] = unique(A(:,2),____)
but can't figure out a slick way to get what I want. I can also imagine a brute-force approach that involves looping through the whole array and doing this "manually", but I feel like there should be a much more elegant (read: clever" solution that I am missing.
I have to process many arrays, and there is no obvious pattern to the duplicates -- some arrays have no duplicates, others have many, some at the beginning, some at the end.
Thanks, all.
Matt
EDIT: I think it should be OK to assume that the arrays are sorted on the first column in ascending order, which I think may be helpful.

Accepted Answer

the cyclist
the cyclist on 4 Jun 2025
I believe this does what you want:
A = [1 0;
2 0;
3 1;
4 2;
5 3;
6 3;
7 3];
[~, ia_last] = unique(A(:,2), 'last', 'stable');
[~, ia_first] = unique(A(:,2), 'first','stable');
A_new = A(ia_last(1):ia_first(end),:)
A_new = 4×2
2 0 3 1 4 2 5 3
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

More Answers (0)

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Products


Release

R2023b

Community Treasure Hunt

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

Start Hunting!