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.
totRow? Or do you want to get rid of all of those rows and replace, say, the first withtotRow? – march Nov 26 '15 at 03:32posand add the rowtotRow, so I have the idea of drop + join, but I am wondering whether it can be done compactly and effectively... – atapaka Nov 26 '15 at 03:34Append[Part[tbl, Complement[Range@Length@tbl, pos]], Total[tbl[[pos]], {2}]]– march Nov 26 '15 at 03:39Append[Delete[tbl, {#} & /@ pos], Total[tbl[[pos]], {2}]]. – march Nov 26 '15 at 03:49totRowquite strange. Why placing it in the last line? Something liketbl[[pos]] = Total /@ tbl[[pos]]; tblis more intuitive in my opinion. – xzczd Nov 26 '15 at 03:58Append[#1[[Complement[Range@Length@#1, #2]]], Total[#[[#2]], {2}]] &[tbl, pos], where tbl and pos are the table and position list. Edit: Actually, just saw march's comment - that's cleaner... – ciao Nov 26 '15 at 08:42{{1, 2, 3}, 10, 20, {4, 8, 12}, 30, {6, 12, 18}}for the table constructed astbl = Table[i*j, {i, 6}, {j, 3}];. So it does not insert a single row but rather inserts individual elements of the result into each of the original rows. But it would be great if this approach would work. – atapaka Nov 26 '15 at 15:42