def c(matrix):
result = numpy.zeros(matrix.shape)
sums = numpy.zeros(matrix.shape[0])
for i in range(matrix.shape[0]):
for j in range(matrix.shape[1]):
sums[i] += matrix[i, j]
for i in range(matrix.shape[0]):
for j in range(matrix.shape[1]):
result[i, j] = matrix[i, j] / sums[i]
return result
Goal of the code
- The function
c takes a 2D array called matrix.
- It returns a new 2D array (
result) in which each row of matrix has been normalised to that its elements sum to 1.
- This means, for each row i, $\sum_j\text{result}[i,j]=1$.
Create a Result Array
result = numpy.zeros(matrix.shape)
matrix.shape gives a tuple $(\text{num\_rows},\text{num\_cols})$.
numpy.zeros(matrix, shape) initialises a 2D array (result) filled with zeros of the same dimensions as matrix.
- This ensures
result is ready to store the normalised values.
Prepare an Array for the Row Sums
sums = numpy.zeros(matrix.shape[0])
matrix.shape[0] is the number of rows in matrix.
sums is a 1D array of length matrix.shape[0], initially all zeros.
- This will track the sum of each row.
Compute the Row Sums
for i in range(matrix.shape[0]):
for j in range(matrix.shape[1]):
sums[i] += matrix[i, j]