Matlab中的小计计算

3

我希望在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];

如果前两列相等,则求第三列的和。有没有一种简单的方法可以做到这一点,而不必循环多次?

欢迎来到 Stack Overflow!你尝试过什么? - Corey Adler
2个回答

5
你可以通过uniqueaccumarray的组合来实现这一点:
%# 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];

0
您可以使用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解决方案发布时还不存在。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接