def b(matrix):
result = numpy.zeros(matrix.shape)
sums = numpy.zeros(matrix.shape[1])
for j in range(matrix.shape[1]):
for i in range(matrix.shape[0]):
sums[j] += matrix[i, j]
for i in range(matrix.shape[0]):
for j in range(matrix.shape[1]):
result[i, j] = matrix[i, j] / sums[j]
return result
def b(matrix):
...
return result
The function is called b and takes one argument called matrix
, which is assumed to be a 2D numpy array. It returns a new 2D array (called result
) that is the normalised version of matrix
along its columns.
result = numpy.zeros(matrix.shape)
matrix.shape
returns a tuple (num_rows, num_cols)
corresponding to the dimensions of the 2D numpy array.numpy.zeros(matrix.shape)
creates an array of zeros with the exact same dimensions as matrix
.result
array will eventually hold the normalised values. By initialising it with zeros, the function ensures it has the right shape from the start, and then updates each element with the normalised value in the subsequent loops.sums = numpy.zeros(matrix.shape[1])
matrix.shape[1]
is the number of columns in the matrix
.numpy.zeros(matrix.shape[1])
creates a 1D array with length equal to the number of columns. This array, called sums
, is used to store the sum of each column.for j in range(matrix.shape[1]):
for i in range(matrix.shape[0]):
sums[j] += matrix[i, j]
j
) and then each row (inner loop: i
).