Delete all rows except last one with that index

13 views (last 30 days)
I have two columns of data where I use the first as the ID and I want to delete all the rows with the same ID except for the last one with that ID. I cannot use unique as the corresponding value in the second column will always be different.
This is an over simplified example but should help explain what I mean:
2 12
4 6
5 24
5 39
5 15
5 18
11 18
14 5
14 6
23 5
Ideally I would hope to end up with the following as I always need to keep the last row with that ID:
2 12
4 6
5 18
11 18
14 6
23 5
Any help would be greatly appreciated.

Accepted Answer

Star Strider
Star Strider on 29 Jun 2017
Use the second output from the unique function on the flipud of your matrix:
M = [2 12
4 6
5 24
5 39
5 15
5 18
11 18
14 5
14 6
23 5];
Mf = flipud(M);
[~,ix] = unique(Mf(:,1));
Result = Mf(ix,:)
Result =
2 12
4 6
5 18
11 18
14 6
23 5
The second output of unique is the first instance of each unique element, so since your data are ordered, using flipud first returns the last element.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!