我有一个 150x2 矩阵,其中第一列包含可视为“分组变量”的数字,第二列包含与这些分组变量关联的值。所以一个小的 12x2 版本看起来像这样
200741 5441
200741 5524
200741 5428
200742 5670
200742 5668
200742 5559
200742 5215
200743 5184
200743 5473
200743 5496
200743 5568
200743 5702
我想找到与每个分组变量关联的值的最后一个值。因此,上面的示例将产生最后一个元素 5428(对于变量 200741)、最后一个元素 5215(对于变量 200742)和最后一个元素 5702(对于分组变量 200743)。在 coumn1 中找到分组变量的唯一值后,如何获取每个分组变量对应的 column2 中的最后一个元素?这怎么能在 Matlab 中完成?
最佳答案
如果第一列是排序并且包含正整数,您可以使用accumarray
(无可否认地稍微拉伸(stretch)了一下):
result = nonzeros(accumarray(A(:,1), A(:,2), [], @(x) x(end), 0, true));
注意事项:
排序要求源于这样一个事实,即根据 documentation ,
If the subscripts in
subs
are not sorted with respect to their linear indices, thenaccumarray
might not always preserve the order of the data in val when it passes them tofun
所以
@(x) x(end)
不会总是给出 last 元素。accumarray
的稀疏版本(第五个参数true
)用于分组值较大的情况(如示例中所示)。
关于matlab - 如何在一组分组变量中找到最后一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28460280/