# Specific aggregation of matrix elements

Let us consider the matrix 'x1':

x1 = {{1, 2, 3, m}, {4, 5, 6, n}, {7, 8, 9, o}, {10, 11, 12, o}}

MatrixForm[x1]


From the matrix 'x1' we compute the matrix 'x2':

x2 = Table[Sum[Sum[x1[[k1, k2]], {k2, 1, j}], {k1, 1, i}], {i, 1, Length[x1[]]}, {j, 1, Length[x1[[All, 1]]]}]

MatrixForm[x2]


The problem is that the code for the calculation of 'x2' is very slow for large matrix 'x1'. How else can calculate the matrix 'x2'?

ralph

Reference Accumulate and Map:

x1 = {{1, 2, 3, m}, {4, 5, 6, n}, {7, 8, 9, o}, {10, 11, 12, o}};

x2 = Accumulate[Accumulate /@ x1];

x2 // MatrixForm


$\left( \begin{array}{cccc} 1 & 3 & 6 & m+6 \\ 5 & 12 & 21 & m+n+21 \\ 12 & 27 & 45 & m+n+o+45 \\ 22 & 48 & 78 & m+n+2 o+78 \\ \end{array} \right)$

Equivalently:

Map[Accumulate, x1, {0, 1}]

• nice ! we can also get rid of Map with Apply and SlotSequence like Accumulate[Accumulate[{##}] & @@@ x1] – Ali Hashmi Jun 4 '17 at 12:55
• @AliHashmi Thank you. However I don't see why one would prefer Apply here as it makes the code more complicated rather than simpler, and it will unpack packed arrays. – Mr.Wizard Jun 4 '17 at 13:12
• @Mr.Wizard thanks forgot about unpacking of packed arrays. Btw, does it mean that Map will not unpack a packed array? – Ali Hashmi Jun 4 '17 at 13:52
• @Ali It should not, but of course the function that is mapped will unpack if it cannot handle a packed array. You can evaluate On["Packing"] and see for yourself (watch for messages). – Mr.Wizard Jun 4 '17 at 14:02
• @Mr.Wizard i just saw your second solution now. Its very elegant. +1 ! – Ali Hashmi Jun 4 '17 at 14:09