代码
import numpy as np
def matrix_multiplication(matrix_1, matrix_2):
h1,w1 = matrix_1.shape
h2,w2 = matrix_2.shape
answer = []
temp_answer = 0
assert w1 == h2, "shape mismatching, check the shape of two input matrix"
for i in range(h1):
for k in range(w2):
for j in range(w1):
temp_answer = temp_answer + matrix_1[i][j] * matrix_2[j][k]
answer.append(temp_answer)
temp_answer = 0
answer = np.reshape(answer, (h1, w2))
return answer
# 从键盘输入两个矩阵的形状以及它们对应的值
matrix_1_shape = input("Input matrix_1's shape, use ',' to separate, eg:1,3 means the (1,3) shape matrix":)
matrix_1 = input("Input matrix_1's value, use ',' to separate,such'1,2,3' for the (1,3) shape matrix":)
matrix_2_shape = input("Input matrix_2's shape, use ',' to separate, eg:1,3 means the (1,3) shape matrix:")
matrix_2 = input("Input matrix_2, use ',' to separate, such'1,2,3' for the (1,3) shape matrix:")
matrix_1_shape = [int(x) for x in matrix_1_shape.split(',')]
matrix_2_shape = [int(x) for x in matrix_2_shape.split(',')]
matrix_1 = np.array([int(x) for x in matrix_1.split(',')])
matrix_2 = np.array([int(x) for x in matrix_2.split(',')])
matrix_1 = np.reshape(matrix_1,(matrix_1_shape[0],matrix_1_shape[1]))
matrix_2 = np.reshape(matrix_2,(matrix_2_shape[0],matrix_2_shape[1]))
print(matrix_1.shape,matrix_2.shape)
c = matrix_multiplication(matrix_1, matrix_2)
print(c.shape)
d = np.dot(matrix_1, matrix_2) # 与numpy自带的矩阵相乘函数结果进行对比
print(d.shape)
assert (c == d).all(), "logic error, check your code"
print('well done')
运行结果:
Input matrix_1's shape, use ',' to separate, eg:1,3 means the (1,3) shape matrix:1,2 Input matrix_1's value, use ',' to separate,such'1,2,3' for the (1,3) shape matrix:1,2 Input matrix_2's shape, use ',' to separate, eg:1,3 means the (1,3) shape matrix:2,1 Input matrix_2, use ',' to separate, such'1,2,3' for the (1,3) shape matrix:1,2 (1, 2) (2, 1) (1, 1) (1, 1) well done



