accumarray()\'s val
argument must be a vector. In my case I need columns of a matrix to be summed (or averaged). Is there a function or a method to achieve thi
Perhaps a more intuitive (maybe more efficient) way borrowed from MATLAB Answers (the original answer assumes column-major inputs so I transposed them):
[xx, yy] = ndgrid(labels,1:size(X, 1));
totals = accumarray([yy(:) xx(:) ], reshape(X.', 1, []));
Example:
X = [1 2 3 4; 5 6 7 8];
labels = [2; 1; 3; 1];
gives
totals = [6 1 3; 14 5 7]
.
If you want to do this row-wise then there's no need to transpose, just:
[xx, yy] = ndgrid(labels,1:size(X, 2));
totals = accumarray([xx(:) yy(:)], X(:));