[英]Summing over rows of a matrix in Matlab with the same index
I have a matrix A
in Matlab of dimension hxk
where element ik
reports an index from {1,2,...,s<=h}
. 我在维度hxk
Matlab中有一个矩阵A
,其中元素ik
报告来自{1,2,...,s<=h}
的索引。 The indices can be repeated across rows. 索引可以跨行重复。 I want to obtain B
of dimension sx(k-1)
where element j
is the sum of the rows of A(:,1:k-1)
with index j
. 我想获得维度sx(k-1)
B
,其中元素j
是具有索引j
的A(:,1:k-1)
的行的总和。 For example if 例如,如果
A = [0.4 5 6 0.3 1;
0.6 -0.7 3 2 2;
0.3 4.5 6 8.9 1;
0.9 0.8 0.7 3 3;
0.7 0.8 0.9 0.5 2]
the result shoud be 结果应该是
B = [0.7 9.5 12 9.2;
1.3 0.1 3.9 2.5;
0.9 0.8 0.7 3]
You'd need a multi-column version of accumarray
. 你需要一个多列版本的accumarray
。 Failing that, you can use sparse
as follows: 如果失败了,你可以使用sparse
如下:
[m n] = size(A);
rows = ceil(1/(n-1):1/(n-1):m);
cols = repmat(1:n-1,1,m);
B = full(sparse(A(rows,end), cols, A(:,1:end-1).'));
cell2mat(arrayfun(@(x) sum(A(A(:,end)==x,1:end-1),1), unique(A(:,end)), 'UniformOutput', false))
关键点是选择行A(A(:,end)==x,1:end-1)
其中x
是A(:,end)
的唯一元素
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.