# Sum selected rows/columns and replace them with the sum

I have the code:

pos = {2, 3, 5};
tbl = Table[i*j, {i, 6}, {j, 3}];
totRow = Total /@ tbl[[pos]];


which defines some row indices (pos) and a table and some of all rows given by indices pos. However, I would like to do in mathematica way (so probably no fors) sum those rows and replace them by that single total row, which in my example has the name totRow. What is the most effective way. I was thinking succession of drop, join but is there a better way?

To supply an example:

pos = {2, 3, 5};
tbl = Table[i*j, {i, 6}, {j, 3}];
totRow = Total /@ tbl[[pos]];
finTbl = Join[Delete[tbl, Partition[pos, 1]], {totRow}];
totRow
TableForm[tbl]
TableForm[finTbl]


gives an idea, the three rows from tbl at indices given by pos are deleted and the totRow added. So this works but looks clumsy, I am just curious whether there is proper or better way.

UPDATE: I changed the examples so that the original table is made of i*j for better legibility.

• I'm a little unclear on this: do you want to replace each of those rows with a copy of totRow? Or do you want to get rid of all of those rows and replace, say, the first with totRow? – march Nov 26 '15 at 3:32
• Sorry about that, I want to get rid of all the rows indices of which are specified by pos and add the row totRow, so I have the idea of drop + join, but I am wondering whether it can be done compactly and effectively... – leosenko Nov 26 '15 at 3:34
• I don't understand. Please try to be more explicit – Dr. belisarius Nov 26 '15 at 3:38
• Right: perhaps an example with the expected output would be helpful. But, perhaps this? Append[Part[tbl, Complement[Range@Length@tbl, pos]], Total[tbl[[pos]], {2}]] – march Nov 26 '15 at 3:39
• Or Append[Delete[tbl, {#} & /@ pos], Total[tbl[[pos]], {2}]]. – march Nov 26 '15 at 3:49

(*Generate table*)
table = Table[RandomReal[], {6}, {3}];

(*Declare positions*)
pos = {2, 3, 5};

(*Carry out addition, removal and modification*)
Append[Delete[table, Partition[pos, 1]], #] &[Total@# &[table[[#]] & /@ pos]]


The way you are doing it seems just fine. If you want to make it less clear what you are doing, and add some shorthand notation you could rewrite it like this:

finTbl = tbl~Delete~Transpose@{pos}~Join~{Total /@ tbl[[pos]]}


(it hurts my brain to try and read code written using infix notation, but I was trying to do it with the smallest number of characters)

As an oneliner. You don't need Table to create a random matrix

Append[Delete@##, Plus @@@ Extract@##] & @@ {RandomReal[1, {6, 3}], List /@ {2, 3, 5}};

f[table_, pos_] := Append[Delete[table, List /@ pos], Tr /@ table[[pos]]]

finTbl = f[tbl, pos]