Index amount

Let's pretend that

A = [10 20 30 40]; idx = [1 1 1 2]; result = [0 0]; 

I need to sum A by indices in idx so that

 result(1) = A(1) + A(2) + A(3); result(2) = A(4); 

I implemented the code

 for i=1:length(idx) result(idx(i)) += A(i); end 

How can I convert it to a more standard octave code, if possible, single-line?

+4
source share
1 answer

Take a look at accumarray , it does exactly what you are asking for, it only needs the first input as a column:

 A = [10 20 30 40]; idx = [1 1 1 2]; result = accumarray(idx',A) result = 60 40 

and yes, this also works in octave;) ( link )

+2
source

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


All Articles