In matlab how to sum rows of a matrix according to specified bins/subscripts in a non-iteration manner?

Viewed 61

This question generalizes the previous one Any way for matlab to sum an array according to specified bins NOT by for iteration? Best if there is buildin function for this. I am not sure, but I tried and the answers in previous post seem not to work with matrices.

For example, if

A = [7,8,1,1,2,2,2]; % the bins or subscripts
B = [2,1; ...
     1,1; ...
     1,1; ...
     2,0; ...
     3,1; ...
     0,2; ...
     2,4]; % the matrix

then the desired function "binsum" has two outputs, one is the bins, and the other is the accumulated row vectors. It is adding rows in B according to subscripts in A. For example, for 2, the sum is [3,1] + [0,2] + [2,4] = [5,6], for 1 it is [1,1] + [2,0] = [3,1].

[bins, sums] = binsum(A,B);

bins = [1,2,7,8]
sums = [2,1;
        1,1;
        3,1;
        5,6]

The first method accumarray says its "val" argument can only be a scalar or vector. The second method spare seems not to accept a vector as the value "v" for each tuple (i,j) neither. So I have to post for help again, and it is still not desired to use iterations to go over the columns of B to do this.

I am using 2017a. Many thanks again!

2 Answers
Related