1
$\begingroup$

I have a table that looks like

Table[m, {k, 10}, {j, k}, {i, j}]

where, m is a square matrix that depends on the indices $i, j$, and $k$. I want to add all of the m matrices in the table. What is the most efficient way to do it?

If there are only two indices, I can do

Total[Apply[Join, Table[m, {k, 10}, {j, k}]]]

But this is not very fast.

I am trying to avoid nested sums, any suggestions are greatly appreciated!

$\endgroup$
  • $\begingroup$ Plus@@(Table[m, {k, 10}, {j, k}, {i, j}])? $\endgroup$ – Algohi Apr 3 '15 at 22:23
  • $\begingroup$ Flatten[result,2]//Total (result being the result of your table) should do what you're after... $\endgroup$ – ciao Apr 3 '15 at 22:26
  • $\begingroup$ Thank you both. Algohi your method does not seem to work. rasher your method works, just to be clear if I have more indices I will need to Flatten at a higher level before the Total correct? Do you have any alternative approaches to this task? $\endgroup$ – user64620 Apr 3 '15 at 22:38
  • $\begingroup$ Change Table to Sum. $\endgroup$ – 2012rcampion Apr 3 '15 at 22:49
  • $\begingroup$ @user64620: Yes. I assumed you had the table and/or needed it as some intermediate result. If not, using Sum as commented by 2021rcampion is cleaner... $\endgroup$ – ciao Apr 4 '15 at 0:46
1
$\begingroup$

Total takes a second argument which specifies the levels to sum together. In your case you want to preserve the lowest two levels so you need to total down to level -3:

Total[Table[m, {k, 10}, {j, k}, {i, j}], -3]

This will work if you have more indices.

$\endgroup$
  • $\begingroup$ Thank you, this is very useful. $\endgroup$ – user64620 Apr 4 '15 at 18:08

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.