python请输入两个矩阵,用循环结构写矩阵点乘。例如有两个矩阵A和B,它们的维度分别为(m,n)和(n,p),矩阵点乘的结果C的维度为(m,p)
时间: 2023-05-26 12:04:57 浏览: 127
用python实现矩阵乘法
下面是一种Python代码实现方式:
m = int(input("Enter the number of rows for matrix A: "))
n = int(input("Enter the number of columns for matrix A and rows for matrix B: "))
p = int(input("Enter the number of columns for matrix B: "))
A = []
for i in range(m):
row = []
for j in range(n):
element = int(input("Enter element for matrix A at position ({},{}) ".format(i, j)))
row.append(element)
A.append(row)
B = []
for i in range(n):
row = []
for j in range(p):
element = int(input("Enter element for matrix B at position ({},{}) ".format(i, j)))
row.append(element)
B.append(row)
C = []
for i in range(m):
row = []
for j in range(p):
value = 0
for k in range(n):
value += A[i][k] * B[k][j]
row.append(value)
C.append(row)
print("The resulting matrix C is:")
for row in C:
print(row)
首先输入矩阵A的行数m,同时也是矩阵C的行数,然后输入矩阵A的列数和矩阵B的行数n,以及矩阵B的列数p。接下来循环输入矩阵A和矩阵B的各个元素,然后使用三重循环计算矩阵C中的每个元素,最后输出矩阵C。
阅读全文