Remove duplicates from array, some first and some last
조회 수: 6 (최근 30일)
이전 댓글 표시
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
채택된 답변
the cyclist
2025년 6월 4일
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),:)
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!