Delete all rows except last one with that index

4 次查看(过去 30 天)
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.

采纳的回答

Star Strider
Star Strider 2017-6-29
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.

更多回答(0 个)

类别

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

标签

Community Treasure Hunt

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

Start Hunting!

Translated by