matlab - 在不使用 MATLAB 中的 for 循环的情况下计算列中某些行(基于 uniqId)的总和

标签 matlab sum

我有一个矩阵:

raw = [ 2001 1000 ; 2001 2000 ; 2001 1000 ; 2001 1000 ; 2001 2000 ; 5555 nan ; 5555 10000 ; 5555 20000 ; 5555 5000 ; 5555 20000 ; 5555 30000 ; 7777 1000 ; 7777 2000 ; 7777 3000 ; 7777 nan] ;

我需要根据 Col1 中的 uniqId 找到 Col2 中每最后 4 行(对于每个 uniqId)的总和。 Col2 中也可能包含 NaN。我想要的答案是:

[2001 nan; 2001 nan; 2001 nan; 2001 5000; 2001 6000; 5555 nan; 5555 nan; 5555 nan; 5555 nan; 5555 55000; 5555 75000; 7777 nan 7777 nan 7777 nan ; 7777 nan] ;

原始矩阵只有 >= 4 行数据的元素。我不能使用 for 循环。如果可能,请帮助我使用矢量化形式。如果需要,我可以使用 while 循环。

最佳答案

您可以使用函数 UNIQUE 来做到这一点和 ACCUMARRAY .下面假设每个组至少有 4 个元素。原始数据中存在的任何 NaN 值都将导致包含该值的求和窗口的值为 NaN:

[~,~,index] = unique(raw(:,1));  %# Get the indices for the unique values
sumFcn = @(x) {sum(hankel([nan(3,1); x(1:numel(x)-3)],...  %# Anonymous function
                          x(numel(x)-3:end)),2)};          %#   to get the sum
                                                           %#   over each window
                                                           %#   of four values
sumPerID = accumarray(index,raw(:,2),[],sumFcn);  %# Compute the windowed sum
                                                  %#   for each unique ID
raw(:,2) = vertcat(sumPerID{:})  %# Place the results back into the second
                                 %#   column of raw
raw =

        2001         NaN
        2001         NaN
        2001         NaN
        2001        5000
        2001        6000
        5555         NaN
        5555         NaN
        5555         NaN
        5555         NaN
        5555       55000
        5555       75000
        7777         NaN
        7777         NaN
        7777         NaN
        7777         NaN

关于matlab - 在不使用 MATLAB 中的 for 循环的情况下计算列中某些行(基于 uniqId)的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4925724/

相关文章:

ruby - 如何在ruby中获取字符串数组的总和

Mysql SUM() TIME 格式错误

matlab - 如何在 MATLAB 中可视化稀疏矩阵?

matlab - MATLAB 中包含 : Time, 频率和功率谱密度的 3-D 图

matlab - 如何在MATLAB中提取N个最小点和N个最大点(忽略数组中的重复点)?

java - 如何使用 LocalTime 在 Java 中对两次求和?

matlab - 用分布式粒子拟合图像中自由区域的最大圆

algorithm - 通过内置命令在matlab中计算所有N位字符串

c# - 是否可以选择一列的总和,按另一列分组?

VBA:添加不规则范围