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/

相关文章:

sum - 电源 BI : Simple addition give wrong result

r - ifelse 语句中的 sum() 条件

javascript - 使用 Node 打开 MATLAB GUI

matlab - 什么时候矢量化是比循环更好或更差的解决方案?

performance - 对给定的一系列数字求和,以便尽可能多地重置求和算法

mysql - 求和到某个点 - MySql

mysql - 如何连续总结过去30天?

matlab - 如何在 matlab 中读取具有可变十六进制值列的文本文件?

python - python 中的 interp2 函数类似于 MATLAB interp2

matlab - 是否有正确的方法来绘制比率直方图?