# Convenient methods to sum select rows (or cols) of a matrix? [duplicate]

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?

-

## marked as duplicate by Mr.Wizard♦Apr 4 '13 at 1:07

Duplicate: mathematica.stackexchange.com/q/3069/5 – R. M. Apr 3 '13 at 22:47
@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. – 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}]]


or

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 [[...]].

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

You can dimension matrix with RandomInteger.

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


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