我有一个矩阵:
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/