MATLAB: On the use of the accumarray function

accumarray

Could someone please explain to me how the accumarray function works. For example:
val = 101:105;
subs = [1; 2; 4; 2; 4];
A = accumarray(subs,val)
A =
101
206
0
208
I cant understand why it performs the following calculations:
101 % A(1) = val(1) = 101
206 % A(2) = val(2)+val(4) = 102+104 = 206
0 % A(3) = 0
208 % A(4) = val(3)+val(5) = 103+105 = 208

Best Answer

Accumarray uses each sub as an index into the val vector. It then takes all values with this index and performs the operation on it (the dedault being sum)
Above:
  1. The index 1 is used onces corresponding to 101. 101 plus nothing else is 101.
  2. The index 2 is used twice corresponding to 102 and 104, these two numbers are summed.
  3. There is no occurence of index 3 so it is zero. (See note below)
  4. The index 4 corresponds to to 103 and 105, the rest is history...
Note
  • accumarray uses fillval to fill in elements who have no subs. You can set it using the 5th input to accumarray
-An accumarray fan