Delete rows with the same data in the matrix

Let's say I have a matrix, and I want to get rid of the duplicates and keep them once, so I can use unique, but I want to get rid of the rows that have the same data but are in different positions and keep them once, so what do I do?
The starting matrix = [1 1;1 2;2 3;4 5;1 1;2 1;3 2];
I want the result = [1 1;1 2;2 3;4 5]; or [1 1;2 1;3 2;4 5];
Can anyone help me with this as I'm completely new with MATLAB. I would be grateful.

 採用された回答

Jan
Jan 2022 年 11 月 5 日
編集済み: Jan 2022 年 11 月 6 日

2 投票

x = [1 1;2 1;2 3;4 5;1 1;1 2;3 2]; % Swapped [1,2] and [2,1]
sx = sort(x, 2); % Sort the rows:
[ux, ix] = unique(sx, 'rows', 'stable');
% Solution 1: sorted order
ux
ux = 4×2
1 1 1 2 2 3 4 5
% Solution 2: original order
x(ix, :)
ans = 4×2
1 1 2 1 2 3 4 5

6 件のコメント

Rik
Rik 2022 年 11 月 8 日
@Chenglin Li Flags are meant to attract attention from site admins.
I see this answer has already received an upvote. If you want to express your gratitude beyond that, you should post a comment instead of a flag.
Chenglin Li
Chenglin Li 2022 年 11 月 8 日
Sorry, I don't know the meaning of Flags in mathwork, but thank you very much for your answer which helped me a lot.
Bruno Luong
Bruno Luong 2022 年 11 月 8 日
Jan's answer is clearly better than the accepted answer
Chenglin Li
Chenglin Li 2022 年 11 月 8 日
ok!!!
Jan
Jan 2022 年 11 月 8 日
Unfortunately the formerly accepted answer was deleted. Its runtime grows quadratically with the size of the input. Although the code I've suggested is faster, it was valuable to see the different approaches to learn for own implementations.
Chenglin Li
Chenglin Li 2022 年 11 月 8 日
Yes, I thought of using the unique function before, but I didn't sort it.Thank you very much

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeProgramming についてさらに検索

質問済み:

2022 年 11 月 5 日

コメント済み:

2022 年 11 月 8 日

Community Treasure Hunt

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

Start Hunting!

Translated by