我试图编写一个将两个矩阵相乘的函数。矩阵由诸如[[1, 2], [3, 4]]
之类的列表中的列表表示。尽管它给出了结果,但这是不正确的。
def Matrice_multiplicator(a, z):
if len(a[0])==len(z):
m=Matrice_create(len(a))
b=0
c=0
k=1-1
while b<len(a):
for i in range(len(a[b])):
while c<len(a[0]):
k+=a[b][c]*z[c][b]
print(k)
c+=1
m[b].append(k)
b+=1
return m
else:
return "Not multiplicable"
答案 0 :(得分:2)
标准Python中的矩阵乘法看起来像:
def matrix_multiplication(A, B):
a = len(A)
b = len(A[0])
c = len(B[0])
if b != len(B):
print (f"Wrong combination of dimensions: {a}x{b} and {len(B)}x{c}")
else:
return [[sum([A[i][k]*B[k][j] for k in range(b)])
for j in range(c)]
for i in range(a)]
A = [[1, 2, 3],
[4, 5, 6]]
B = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]]
print(matrix_multiplication(A, B))
结果:
[[38, 44, 50, 56],
[83, 98, 113, 128]]