我在维度A
的Matlab中有一个矩阵hxk
,其中元素ik
报告来自{1,2,...,s<=h}
的索引。索引可以跨行重复。我想获得维度B
的{{1}},其中元素sx(k-1)
是j
行与索引A(:,1:k-1)
的行的总和。例如,如果
j
结果应该是
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]
答案 0 :(得分:2)
您需要accumarray
的多列版本。如果不这样做,您可以按如下方式使用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).'));
答案 1 :(得分: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)
的唯一元素