Remove duplicate elements in an Array based on one of the columns
11 views (last 30 days)
Show older comments
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 !
0 Comments
Accepted Answer
Guillaume
on 11 Feb 2016
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 Comments
Akash Menon
on 13 Feb 2019
Edited: Akash Menon
on 13 Feb 2019
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:
Vijay
on 30 Sep 2020
Not sure, but this didn't work for me.
I found the following simple solution to the same problem.
More Answers (0)
See Also
Categories
Find more on Matrix Indexing 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!