【问题标题】:Matlab running max by groupMatlab按组运行最大
【发布时间】:2016-03-15 11:52:16
【问题描述】:

在 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),但这里的问题更难,因为我想跑到最高分。

R 中有一个类似的问题,但我希望能够在 Matlab 中做到这一点。 Finding running maximum by group in R

谢谢!

【问题讨论】:

    标签: matlab max groupwise-maximum


    【解决方案1】:

    如果您有最新的 Matlab 版本,您可以使用 accumarray 和 cummax,如下所示。请注意,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
    

    【讨论】:

      猜你喜欢
      • 2011-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多