Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

This question already has an answer here:

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?

share|improve this question
1  
Duplicate: mathematica.stackexchange.com/q/3069/5 –  rm -rf 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
add comment

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

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2 Answers

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

share|improve this answer
3  
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
add comment

You can dimension matrix with RandomInteger.

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

Adding second column to fourth.

m[[All, 2]] + m[[All, 4]]
share|improve this answer
add comment

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