Any way for Matlab to sum the array according to the indicated cells NOT for iteration? Better if there is a buildin function for this function

For example, if

A = [7,8,1,1,2,2,2]; % the bins (or subscripts)
B = [2,1,1,1,1,1,2]; % the array

then the desired function “binum” has two outputs, one is the bunkers, and the other is the sum. He simply adds the values ​​to B according to the indices in A. For example, for 2 the sum is 1 + 1 + 2 = 4, for 1 it is 1 + 1 = 2.

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

bins = [1,2,7,8]
sums = [2,4,2,1]

Elements in “silos” do not have to be ordered, but must correspond to elements in “sums”. This, of course, can be done using "for" iterations, but "for" iterations are not required because there is a performance issue. Best if there is a build function for this.

Thank you so much!

+4
3

accumarray

A = [7,8,1,1,2,2,2]; % the bins (or subscripts)
B = [2,1,1,1,1,1,2]; % the array

sums = accumarray(A.', B.').';
bins = unique(A);

:

>> bins
bins =

   1   2   7   8

sums =

   2   4   0   0   0   0   2   1

sums , sums(2) = 4. nonzeros , bins(n) sums(n)

sums = nonzeros(sums).';

sums =

   2   4   2   1

, sums :

sums = nonzeros(accumarray(A.', B.')).';
+5

sparse, find.

  • , A ,

    [bins, ~, sums] = find(sparse(A, 1, B));
    

    , sparse ( ) ( ).

  • A , unique, find nonzeros:

    [bins, ~, labels]= unique(A);
    sums = nonzeros(sparse(labels, 1, B));
    
+5

Here is a solution using sortand cumsum:

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

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


All Articles