有一个大小为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.
更多推荐
如何按多列求和?
发布评论