1
$\begingroup$

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[[1]]]}, {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

$\endgroup$
4
$\begingroup$

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}]
$\endgroup$
  • $\begingroup$ nice ! we can also get rid of Map with Apply and SlotSequence like Accumulate[Accumulate[{##}] & @@@ x1] $\endgroup$ – Ali Hashmi Jun 4 '17 at 12:55
  • $\begingroup$ @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. $\endgroup$ – Mr.Wizard Jun 4 '17 at 13:12
  • $\begingroup$ @Mr.Wizard thanks forgot about unpacking of packed arrays. Btw, does it mean that Map will not unpack a packed array? $\endgroup$ – Ali Hashmi Jun 4 '17 at 13:52
  • 1
    $\begingroup$ @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). $\endgroup$ – Mr.Wizard Jun 4 '17 at 14:02
  • $\begingroup$ @Mr.Wizard i just saw your second solution now. Its very elegant. +1 ! $\endgroup$ – Ali Hashmi Jun 4 '17 at 14:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.