如何按多列求和? [英] How group sums by multiple columns?

查看:157
本文介绍了如何按多列求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个大小为n x 3的矩阵,我想按组将第一行和第二列定义的第三行值相加.

举一个具体的例子

A =[0.0050    0.0050    0.0050
    0.0050    0.0050    0.0150
    0.0050    0.0050    0.0250
    0.0050    0.0050    0.0350
    0.0050    0.0150    0.0050]

我想对第三列求和,以便得到矩阵

SumA = [0.05 0.05 0.8; 0.05 0.15 0.005];

我试图通过调用accumarray(A(:,[1 2]),A(:,3))创建组,但返回错误: 首先输入的SUBS必须包含正整数下标.

然后我尝试通过首先创建来解决此问题

ind = A(:, [1,2])*1000;

然后

accumarray(ind, A(:,3))

但是它返回了一个5 x 15的矩阵,这不是我想要得到的结果.

有人知道如何对行进行求和,这些行按所选列的组合(相当于SQL SELECT a,b,SUM(c)FROM A GROUP BY a,b)分组吗?

谢谢!

解决方案

[~,~,ind]=unique(A(:,1:2),'rows')为您提供了一个对accumarray有用的下标/索引数组.那里的第一个参数的下标需要引用第二个参数的位置(即列向量A(:,3).不确定为什么要期望2 x 5的数据矩阵而不是索引来在这里做任何事情.

ans(ind)将为您提供一个列向量,该列向量的行数与A相同.

Having a matrix of size n x 3 I would like to sum 3rd row values by groups, defined by 1st and 2nd column.

Given a specific example

A =[0.0050    0.0050    0.0050
    0.0050    0.0050    0.0150
    0.0050    0.0050    0.0250
    0.0050    0.0050    0.0350
    0.0050    0.0150    0.0050]

I would like to sum the third column such that I would get a matrix

SumA = [0.05 0.05 0.8; 0.05 0.15 0.005];

I tried to create groups by calling accumarray(A(:,[1 2]), A(:,3)) but it returns an error: First input SUBS must contain positive integer subscripts.

Then I tried to work around by first creating

ind = A(:, [1,2])*1000;

and then

accumarray(ind, A(:,3))

but it returned a 5 x 15 matrix which is not the result I wanted to get.

Does anyone know how to sum rows, grouped by the combination of selected columns (equivalent to SQL SELECT a, b, SUM(c) FROM A GROUP BY a, b)?

Thanks!

解决方案

[~,~,ind]=unique(A(:,1:2),'rows') gives you a subscript/index array useful for accumarray. The subscripts of the first argument there need to refer to positions in the second (i.e. the column vector A(:,3). Not sure why you expect a 2-by-5 matrix of data, not indices, to do anything there.

ans(ind) will give you a column vector with as many rows as A again.

这篇关于如何按多列求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆