python写代码 请输入两个矩阵,用循环结构写矩阵点乘。例如有两个矩阵A和B,它们的维度分别为(m,n)和(n,p),矩阵点乘的结果C的维度为(m,p)
时间: 2023-05-28 12:02:41 浏览: 71
m = int(input("请输入矩阵A的行数:"))
n = int(input("请输入矩阵A和矩阵B的列数:"))
p = int(input("请输入矩阵B的行数:"))
# 初始化矩阵A
matrix_a = []
for i in range(m):
row = []
for j in range(n):
num = float(input("请输入矩阵A第{}行第{}列的数:".format(i+1,j+1)))
row.append(num)
matrix_a.append(row)
# 初始化矩阵B
matrix_b = []
for i in range(n):
row = []
for j in range(p):
num = float(input("请输入矩阵B第{}行第{}列的数:".format(i+1,j+1)))
row.append(num)
matrix_b.append(row)
# 矩阵点乘
matrix_c = []
for i in range(m):
row = []
for j in range(p):
num = 0
for k in range(n):
num += matrix_a[i][k] * matrix_b[k][j]
row.append(num)
matrix_c.append(row)
# 输出结果
print("矩阵A:")
for row in matrix_a:
print(row)
print("矩阵B:")
for row in matrix_b:
print(row)
print("矩阵点乘结果:")
for row in matrix_c:
print(row)
阅读全文