-1

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?

alancalvitti
  • 15,143
  • 3
  • 27
  • 92
  • 1
    Duplicate: http://mathematica.stackexchange.com/q/3069/5 – rm -rf Apr 03 '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 03 '13 at 23:02

2 Answers2

3

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

Vitaliy Kaurov
  • 73,078
  • 9
  • 204
  • 355
2

You can dimension matrix with RandomInteger.

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

Adding second column to fourth.

m[[All, 2]] + m[[All, 4]]
BoLe
  • 5,819
  • 15
  • 33