我希望在Matlab中对表格进行小计。如果两列的值相等,则将该值加起来,并检查是否有条目。
举个例子,源矩阵如下:
A = [1 2 3;
1 2 2;
1 4 1;
2 2 1;
2 2 3];
输出结果应该如下所示:
B = [1 2 5;
1 4 1;
2 2 4];
如果前两列相等,则求第三列的和。有没有一种简单的方法可以做到这一点,而不必循环多次?
unique
和accumarray
的组合来实现这一点:%# find unique rows and their corresponding indices in A
[uniqueRows,~,rowIdx]=unique(A(:,1:2),'rows');
%# for each group of unique rows, sum the values of the third column of A
subtotal = accumarray(rowIdx,A(:,3),[],@sum);
B = [uniqueRows,subtotal];
unique
来获取所有的组,然后使用splitapply
来对它们进行求和。[u, ~, iu] = unique( A(:,1:2), 'rows' ); % Get unique rows & their indices
sums = splitapply( @sum, A(:,3), iu ); % Sum all values according to unique indices
output = [u, sums]
% >> output =
% output =
% 26 7 124
% 26 8 785
% 27 7 800
splitapply
是在R2015b中引入的,因此在accumarray
解决方案发布时还不存在。