def f_b_v3(M):
return M / M.sum(0)
M.sum(0)
:
M
along axis 0 (the “downward” direction in a 2D matrix).M
has shape $(n, m)$, then M.sum(0)
returns a 1D array of length $m$, where each element is the sum of a particular column of M
.M / M.sum(0)
, numpy’s broadcasting rules automatically “stretch” the 1D array of shape $(m,)$ so that each element in column $j$ of M
is divided by the $j$-th value in M.sum(0)
.M
is divided by its own column sum.M
, but now each column sums to 1.How is this different from Version 2?
reshape((1, M.shape[1]))
to make the broadcasting dimension explicit.Overall, Version 3 is a minimalistic one-liner that leverages numpy’s broadcasting to achieve the same result: each element of M
is divided by the sum of its column.