-1
$\begingroup$

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?

$\endgroup$
2
  • 1
    $\begingroup$ Duplicate: mathematica.stackexchange.com/q/3069/5 $\endgroup$
    – rm -rf
    Apr 3, 2013 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$ Apr 3, 2013 at 23:02

2 Answers 2

3
$\begingroup$

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

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

You can dimension matrix with RandomInteger.

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

Adding second column to fourth.

m[[All, 2]] + m[[All, 4]]
$\endgroup$

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