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 CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by