Is there an accumarray() that takes matrix as `val`?

前端 未结 2 1322
情话喂你
情话喂你 2020-12-10 04:02

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

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-10 04:19

    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(:));
    

提交回复
热议问题