我想在matlab中使用表的小计.如果两列的值相等,则取值并添加(如果有)条目.
如果我们举个例子,源矩阵如下:
A = [1 2 3;
1 2 2;
1 4 1;
2 2 1;
2 2 3];
Run Code Online (Sandbox Code Playgroud)
输出看起来像这样:
B = [1 2 5;
1 4 1;
2 2 4];
Run Code Online (Sandbox Code Playgroud)
如果前两列相等,则将第三列相加.有没有一种简单的方法,而不必多次循环?
你可以用组合做到这一点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];
Run Code Online (Sandbox Code Playgroud)