In Matlab, how to sum matrix rows in accordance with the indicated bunkers / indices in non-iterative order?

This question summarizes the previous one. Any way for Matlab to summarize an array according to specified cells NOT for iteration? It is better if there is a buildin function for this . I'm not sure, but I tried, and the answers in the previous post do not seem 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 binum function has two outputs, one is the bins and the other is the accumulated row vectors. He adds rows to B by the indices 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]

accumarray , "val" . , , "v" (i, j). , - , B. ,

2017a. !

+4
2

- :

bins = unique(A);
sums = (A==bins.')*B;

, logical M × N, M - , N - A. sparse logical :

[bins, ~, labels] = unique(A);
sums = sparse(labels, 1:numel(A), true)*B;
+4

sort cumsum:

[s,I]=sort(A);
c=cumsum(B(I,:));
k= [s(1:end-1)~=s(2:end) true];
sums = diff([zeros(1,size(B,2)); c(k,:)])
bins=s(k)
0

Source: https://habr.com/ru/post/1683617/


All Articles