Find certain row out of many rows with the same id
1 次查看(过去 30 天)
显示 更早的评论
I have a matrix whose each row consists of an id column and some other columns with other features of each object. One of the characteristics is a date. Now, some rows of the matrix have the same id and I want to keep only the one with the most recent date. For example, in the table above, the id is in the third column, so, from the second and third row I want to keep only the third, as it has the most recent date. How could I do that in a matrix with many subsets of rows with the same id?
490 673 9987 {'2015-09-10 00:00:00'} 58
491 110556 10233 {'2010-02-22 00:00:00'} 70
492 110556 10233 {'2011-02-22 00:00:00'} 65
0 个评论
采纳的回答
Walter Roberson
2020-6-23
One approach:
sortrows() on the ID column, and the date column in descending order. unique() the ID column with 'stable' and take the second output. Use that to index the sortrows output to get just the first (newest because descending order) entry for each ID.
If necessary re-sort on the first column.
Or...
findgroups() on the ID, and splitapply() specifying a function that will receive the variable entries that are associated with a single ID. The function would datetime() and max() to get the index of the maximum and return that entry from the variables.
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!