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
? $\endgroup$pos
and add the rowtotRow
, so I have the idea of drop + join, but I am wondering whether it can be done compactly and effectively... $\endgroup$Append[Part[tbl, Complement[Range@Length@tbl, pos]], Total[tbl[[pos]], {2}]]
$\endgroup$Append[Delete[tbl, {#} & /@ pos], Total[tbl[[pos]], {2}]]
. $\endgroup$