How to find a specific row in a matrix and eliminate it?

1 回表示 (過去 30 日間)
kyana shayan
kyana shayan 2015 年 12 月 9 日
コメント済み: Guillaume 2015 年 12 月 9 日
Hi everyone, I have a matrix such as this: D0=[1 2;1 4;2 1;3 5;4 1;5 3]. I need to eliminate one of the two rows with same elements. for example, 1 & 2 both involve in rows one and three, so I need to eliminate one of these rows. can any one please help me?

採用された回答

Guillaume
Guillaume 2015 年 12 月 9 日
It looks like you don't care about the ordering of the columns. In that case, it's extremely simple: a) sort the rows (so that [2 1] becomes [1 2]) and b) use unique to remove duplicates
D0 = [1 2;1 4;2 1;3 5;4 1;5 3]
uniquerows = unique(sort(D0, 2), 'rows', 'stable')
%if you don't care about the rows ordering you can omit the 'stable'
  3 件のコメント
kyana shayan
kyana shayan 2015 年 12 月 9 日
one more thing, if the matrix has 3 columns, then sorting will disorder the original matrix. for example, if I use unique function on this matrix: D0=[2 1 4;4 1 2] ,the uniquerows will be: uniquerows=[1 2 4]. but I need [2 1 4] or [4 1 2]. Guillaume,can you give me a hint on this,too ?
Guillaume
Guillaume 2015 年 12 月 9 日
Simply use the second return value of unique to get the indices of the rows that have been kept. Use those indices to get the actual rows:
D0 = [1 2 4;1 4 3;2 1 4;3 5 2;4 1 3;5 3 2]
[~, rowindices] = unique(sort(D0, 2), 'rows'); %'stable' optional
uniquerows = D0(rowindices, :)

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCorrelation and Convolution についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by