Star
Star

Reputation: 2299

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}. 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. 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]

Upvotes: 1

Views: 101

Answers (2)

Yvon
Yvon

Reputation: 2983

cell2mat(arrayfun(@(x) sum(A(A(:,end)==x,1:end-1),1), unique(A(:,end)), 'UniformOutput', false))

The key point is selecting rows A(A(:,end)==x,1:end-1) where x is a unique element of A(:,end)

Upvotes: 1

Luis Mendo
Luis Mendo

Reputation: 112659

You'd need a multi-column version of accumarray. Failing that, you can use sparse as follows:

[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).'));

Upvotes: 2

Related Questions