用Python写一个程序,要求输入两个矩阵,用循环结构写矩阵点乘。例如有两个矩阵A和B,它们的维度分别为(m,n)和(n,p),矩阵点乘的结果C的维度为(m,p)
时间: 2023-05-26 07:04:54 浏览: 128
python如何进行矩阵运算
matrix_a = []
matrix_b = []
# 输入矩阵A
m = int(input("请输入A矩阵的行数:"))
n = int(input("请输入A矩阵的列数:"))
print("请逐行输入A矩阵的元素:")
for i in range(m):
row = []
for j in range(n):
element = int(input("请输入A矩阵第%d行,第%d列的元素:" % (i+1, j+1)))
row.append(element)
matrix_a.append(row)
# 输入矩阵B
n = int(input("请输入B矩阵的行数(应与A矩阵的列数相等):"))
p = int(input("请输入B矩阵的列数:"))
print("请逐行输入B矩阵的元素:")
for i in range(n):
row = []
for j in range(p):
element = int(input("请输入B矩阵第%d行,第%d列的元素:" % (i+1, j+1)))
row.append(element)
matrix_b.append(row)
# 矩阵点乘
matrix_c = []
for i in range(m):
row = []
for j in range(p):
element = 0
for k in range(n):
element += matrix_a[i][k] * matrix_b[k][j]
row.append(element)
matrix_c.append(row)
# 输出结果
print("A矩阵:")
for row in matrix_a:
print(row)
print("B矩阵:")
for row in matrix_b:
print(row)
print("C矩阵(即A矩阵和B矩阵的点乘结果):")
for row in matrix_c:
print(row)
阅读全文