在许多情况下,数学家已将矩阵的* 定义为表示线性代数“点积”。要进行“元素/单元格乘法”,您需要使用 numpy.multiply 或使用一对 for 循环。
用 numpy python3 -m pip install numpy
# EDIT: Don't use numpy.matrix, they are deprecated and will eventually be removed.
# Use numpy.array as seen in @MrNobody33's answer.
# left_matrix = numpy.matrix("1 1 1; 2 2 2; 3 3 3")
# right_matrix = numpy.matrix("1 2 3; 4 5 6; 7 8 9")
left_matrix = numpy.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]])
right_matrix = numpy.array([[1, 2, 3], [4, 5, 6], [2, 4, 6]])
result_matrix = numpy.multiply(left_matrix, right_matrix)
# Use * or numpy.dot for the linear algebra matrix multiplication.
print(result_matrix)
没有 numpy。
left_matrix = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
right_matrix = [[1, 2, 3], [4, 5, 6], [2, 4, 6]]
result_matrix = []
for i in range(len(left_matrix)):
result_matrix.append([])
for j in range(len(left_matrix[0])):
cell_result = left_matrix[i][j] * right_matrix[i][j]
result_matrix[i].append(cell_result)
print(result_matrix)