Remove duplicates from array, some first and some last

6 ビュー (過去 30 日間)
Moe Szyslak
Moe Szyslak 2025 年 6 月 4 日
コメント済み: Moe Szyslak 2025 年 6 月 4 日
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.

採用された回答

the cyclist
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),:)
A_new = 4×2
2 0 3 1 4 2 5 3
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
  1 件のコメント
Moe Szyslak
Moe Szyslak 2025 年 6 月 4 日
Brilliant! Thanks so much for the help.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

タグ

製品


リリース

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by