Reputation: 21152
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?
Upvotes: 4
Views: 4462
Reputation: 11168
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)
Upvotes: 2