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

1 view (last 30 days)
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?

Accepted Answer

Guillaume
Guillaume on 9 Dec 2015
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 Comments
kyana shayan
kyana shayan on 9 Dec 2015
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 on 9 Dec 2015
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, :)

Sign in to comment.

More Answers (0)

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!