def f_c_v1(M):
arySum = M.sum(1)
return M / arySum.reshape((M.shape[0], 1))
arySum = M.sum(1)
sums over axis 1 of the 2D array M
.M
has shape $(n,m)$, M.sum(1)
produces a 1D array of shape $(n,)$ where each entry is the sum of an entire row of M
.
M.sum(1)[0]
is $\sum_jr_{0,j}$.arySum.reshape((M.shape[0], 1))
changes the shape of arySum
from $(n,)$ to $(n,1)$.M
, which is $(n, m)$.arySum
is of shape $(n,1)$, numpy broadcasting rules will align each row sum with all columns in that corresponding row when we perform the division.M / arySum.reshape((M.shape[0], 1))
divides each element of row $i$ of M
by the $i$-th row sum (stored in arySum[i]
).M
unmodified.Suppose you have the following matrix:
1.0 3.0 1.0
2.0 4.0 4.0
6.0 3.0 6.0
4.0 7.0 9.0
Row sums:
arySum
is the 1D array [5.0, 10.0, 15.0, 20.0]
.Reshaping:
arySum.reshaping((4, 1))
becomes:
[
[5.0],
[10.0],
[15.0],
[20.0]
]
This matches the number of rows in M
, but has a single column.
Normalisation:
M / (reshaped arySum)
transforms each element $M[i,j]$ into $\frac{M[i,j]}{\text{arySum}[i]}$.sum
function is used with axis = 1
.M
.