Matlab 运行 最大组

Matlab running max by group

在 Matlab 中,如何计算每个组的数组的最大值 运行(由另一个数组标记 subs)?例如,将数组 subs 视为 3 个学生的标签,并将 val 中对应的值视为考试成绩,我想计算每个学生达到的 运行 最高分数。

>> subs = [1; 3; 1; 1; 3; 2];
>> val = [101 102 103 98 105 106];

所需输出的大小与 val 相同,并给出该学生当前获得的最高分数:

output = [101, 102, 103, 103, 105, 106]

我的数据集非常大,有数百万个条目,所以我想避免使用 for 循环。如果我只想要每个学生的总体最高分数,我会使用 accumarray(subs,val,[],@max) 但这里的问题更加困难,因为我想要 运行-maximum.

R 中也有类似的问题,但我希望能够在 Matlab 中完成。

谢谢!

如果您有最新的 Matlab 版本,您可以先使用 accumarray with cummax as follows. Note that subs needs 进行排序(当然,需要对 vals 应用相同的排序并在最后撤消)。

[subsSorted, ind] = sort(subs); %// make sure grouping variable is sorted, so that
    %// accumarray is stable
result = accumarray(subsSorted, val(ind), [], @(x) {cummax(x).'}); %'// running max of
    %// each group is computed with cummax function
result = [result{:}]; %// concatenate
result(ind) = result; %// undo sorting