What are some convenient methods to sum selected rows or columns in a matrix? This question Summing along rows or columns of a matrix only addresses how to sun entire rows or columns ie, by level.

For example, suppose one wants to add columns 2 and 4 of:

M = Column@Table[RandomInteger[10], {3}, {4}];

Neither MapAt, nor ReplacePart appear useful in this regard.

Of course #[[2]] + #[[4]] & /@ M works for summing columns and Transpose can be used for rows, but that seems like a hack to specify using such syntax. Any better solutions?

  • 1
    $\begingroup$ Duplicate: mathematica.stackexchange.com/q/3069/5 $\endgroup$ – rm -rf Apr 3 '13 at 22:47
  • $\begingroup$ @rm-rf Just a bureaucratic note ;) In this question the output is a single list. In the one you linked - the whole matrix. This is if I understood OP correctly. $\endgroup$ – Vitaliy Kaurov Apr 3 '13 at 23:02

To add rows 1 and 3:

Total@M[[{1, 3}]]

To add columns 2 and 4:

Total /@ M[[All, {2, 4}]]


Total[M[[All, {2, 4}]], {2}] (* Thx to Mike's coment *)

This works with arbitrary number of specific rows and columns. I guess the main point here is being able to specify the specific columns and rows as a list and not as something spread out over different terms and sets of [[...]].

  • 3
    $\begingroup$ No need to Map: Total[m[[All, {2, 4}]], {2}] $\endgroup$ – Mike Honeychurch Apr 3 '13 at 23:11
  • $\begingroup$ @MikeHoneychurch True. I just liked the uniform look of it ;) I'll put it in. $\endgroup$ – Vitaliy Kaurov Apr 3 '13 at 23:47

You can dimension matrix with RandomInteger.

m = RandomInteger[10, {3, 4}]

Adding second column to fourth.

m[[All, 2]] + m[[All, 4]]

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