0

I am looking for a way to do multiple sums simultaneously and as fast as possible. Suppose

a       = [3 4 1 9 8 3 5];
indices = [1 1 2 1 2 1 2];

Then, the result should be a 1x2 array, say, sumz with

sumz = [19 14];

In other words, I sum every element of a with index 1, and put the result to sumz(1). Then, I sum every element of a with index 2, and put the result to sumz(2). and so on.

I know how to do this using for loops, find, etc. What I am looking for is a fast code.

  • 2
    Use [`accumarray`](https://www.mathworks.com/help/matlab/ref/accumarray.html?s_tid=doc_ta): `sumz = accumarray(indices(:),a(:)).'` – EBH Aug 01 '17 at 15:37
  • @EBH Thanks. I have not heard about that function before. It looks quite strong. Let me see if I can handle it using that. – Erdem Koyuncu Aug 01 '17 at 15:39
  • @EBH Thanks. That does it. It also looks accumarray is not a script, but perhaps they did it in C, so it should hopefully be fast. – Erdem Koyuncu Aug 01 '17 at 15:42
  • That is a "built-in" function, written in C or FORTRAN. And this is probably as fast as you can get. See [here](https://stackoverflow.com/questions/38941694/what-is-the-fastest-way-to-count-elements-in-an-array) – EBH Aug 01 '17 at 15:44
  • @EBH Alright; thank you. – Erdem Koyuncu Aug 01 '17 at 17:11

0 Answers0