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!