Search code examples
matlabaccumarray

Explanation of the output of accumarray


I just read the documentation of accumarray and can't manage to understand the second example. The example is the following

val = 101:106';
subs = [1 1; 2 2; 3 2; 1 1; 2 2; 4 1]
subs =

     1     1
     2     2
     3     2
     1     1
     2     2
     4     1
A = accumarray(subs,val)
A =

   205     0
     0   207
     0   103
   106     0

If I do

B=accumarray(subs(:,1),val)
C=accumarray(subs(:,2),val)

then I get

B=

   205
   207
   103
   106

C =

   311
   310

which is logical to me. But why are the numbers of B just arranged in "random" (I guess it's not random, but seems random to me) positions of a 4x2 matrix when I add a 2nd column to subs?


Solution

  • Taken from the matlab documentation of accumarry (Note: The quote below is from the R2012a documentation and does not exactly match the current version)

    The position of an element in subs determines which value of vals it selects for the accumulated vector; the value of an element in subs determines the position of the accumulated vector in the output.

    So in your example the 'random' ordering comes from the positions specified by subs. Breaking down the meaning of subs and the final result we get something like this:

    val = 101:106';
    subs = [1 1; 2 2; 3 2; 1 1; 2 2; 4 1]
    subs =
    
         1     1    <-- take val(1) which is 101 and put it at position [1, 1] in the output
         2     2    <-- put 102 in position [2, 2]
         3     2    <-- put 103 in position [3, 2]
         1     1    <--- ...and so on
         2     2
         4     1
    A = accumarray(subs,val)
    A =
    
       205     0    <--- [1, 1] has value 101+104, [1, 2] has no value
         0   207    <--- [2, 1] has no value, [2, 2] has value 102+105
         0   103    <--- ...and so on
       106     0