Remove duplicate elements in an Array based on one of the columns

6 次查看(过去 30 天)
Hi , I have a matrix 5000x4 in size. It has rows which have the identical elements in the 1st and 2nd column but different elements in the 4th column. I would like to be able to remove the elements where the 1st and 2nd columns are repeated , and Have a smaller value in the corresponding 4th column.
A =[1 2 3 4;
1 2 4 6;
3 5 7 2;
3 5 4 5;
3 5 3 7;]
In this example , i would like to remove the 1st row and the 3rd and 4th rows too. The 4h column of these rows are lesser than the competing rows' 4th column. I hope its not too confusing.
Thanks, Appreciate the help !

采纳的回答

Guillaume
Guillaume 2016-2-11
Here is one way to do it:
A =[1 2 3 4;
1 2 4 6;
3 5 7 2;
3 5 4 5;
3 5 3 7;]
[~, ~, rows] = unique(A(:, [1 2]), 'rows');
todelete = arrayfun(@(r) rows == r & A(:, 4) < max(A(rows == r, 4)), 1:max(rows), 'UniformOutput', false);
A(any(cell2mat(todelete), 2), :) = []
  4 个评论
Akash Menon
Akash Menon 2019-2-13
编辑:Akash Menon 2019-2-13
I have been searching for this solution for a day now! Many thanks! The 'arrayfun' does take a few tens of seconds to run on my PC but it works perfectly. I had a similar case where I had an array with two coloumns.
One was the kilometer points and the other depths. There were many duplicates of the kilometer points (after I had rounded down a bigger dataset) and I only wanted the unique values of those kilometer points but also their corresponding depths- there were a few depths to choose from but they were so close to each other I could choose the max or min value.
Thic code really helped! Hope the screenshots below help others too!
My original matrix (NewMat3):
Code adapted to my case: (i just used the max values as well into the new matrix)
New Matrix:

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by