Filter löschen
Filter löschen

Delete all rows except last one with that index

4 Ansichten (letzte 30 Tage)
R2
R2 am 29 Jun. 2017
Kommentiert: Star Strider am 30 Jun. 2017
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.

Akzeptierte Antwort

Star Strider
Star Strider am 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.
  2 Kommentare
R2
R2 am 30 Jun. 2017
That works perfectly thank you very much!
Star Strider
Star Strider am 30 Jun. 2017
As always, my pleasure!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by