I have a matrix:

I would like to sum all the first non-zero elements of each row so that I get a value of
$$25.5317 + 8.85471 + 6.90018 + 32.9436 + ... $$
and so on and simply ignore zero rows.
Similarly I would like to do the same again for the second non-zero elements from each row so that I get:
$$29.1235 + 11.0472 + 41.2639$$
Answer
tbl = RandomChoice[{.5, .1, .05, .05, .05, .05, .05, .05, .05, .05} ->
Range[0, 9], {10, 10}];
tbl//TableForm

Remove all zeros from tbl and add zeros to the right to make a full array:
PadRight[tbl /. (0) -> Sequence[], Automatic] // TableForm

Then sum each column:
Tr /@ (Transpose@PadRight[tbl /. (0) -> Sequence[], Automatic])
(* {55, 59, 36, 28, 38, 14, 9} *)
Update: To get a matrix with dimensions {nrows, ncolumns} from PadRight change Automatic to {nrows, ncolumns}. So,
Tr /@ (Transpose@PadRight[tbl /. (0) -> Sequence[], {10,10}])
(* {55, 59, 36, 28, 38, 14, 9, 0 ,0, 0} *)
Comments
Post a Comment