Remove duplicates from array, some first and some last
6 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Moe Szyslak
am 4 Jun. 2025
Kommentiert: Moe Szyslak
am 4 Jun. 2025
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.
0 Kommentare
Akzeptierte Antwort
the cyclist
am 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),:)
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!