4

Suppose I have

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

I need to sum A over indexes 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 transform it to more octave-standard code, if possible one-liner?

Oleg Pavliv
  • 20,462
  • 7
  • 59
  • 75
  • Also see a more general question: https://stackoverflow.com/questions/4350735/is-there-an-accumarray-that-takes-matrix-as-val – Yibo Yang Nov 11 '18 at 20:32

1 Answers1

2

Take a look at accumarray, it does exactly what you are asking for, it only needs its 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)

Gunther Struyf
  • 11,158
  • 2
  • 34
  • 58