我想弄清楚如何创建一个点积矩阵。这是我到目前为止所做的代码:
C = [[4,1,9], [6,2,8], [7,3,5]]
D = [[2,9], [5,2], [1,0]]
def prettyPrint(A):
for i in range(len(A)):
line = "{0: >7}".format("|"+str(A[i][0]))
for j in range(1, len(A[i])):
line = line + "{0: >7}".format(str(A[i][j]))
line = line + "|"
print(line)
#for addition of vectors
def matrixADD(A,B):
Z = []
for i in range(len(A)):
row = []
for j in range(len(A[0])):
row.append(A[i][j]+B[i][j])
Z.append(row)
return Z
#for subtraction of vectors
def matrixSUB(A,B):
Z = []
for i in range(len(A)):
row = []
for j in range(len(A[0])):
row.append(A[i][j]-B[i][j])
Z.append(row)
return Z
#for multiplication of vectors
def row(A,i):
Z = []
Z.extend(A[i])
return Z
def col(B,j):
Z = []
for row in B:
Z.append(row[j])
return Z
def dotProduct(x,y):
prod = 0
prod = sum(p*q for p,q in zip(x,y))
return prod
def matrixMUL(A,B):
Z = []
#Need to do.
return Z
print("\nC * D:")
prettyPrint(matrixMUL(C,D))
这matrixMUL(A,B)
是我遇到麻烦的部分。该程序应该通过这种计算:示例:
Z = C * D =
row(C,0) • col(D,0) row(C,0) • col(D,1)
row(C,1) • col(D,0) row(C,1) • col(D,1)
row(C,2) • col(D,0) row(C,2) • col(D,1)
Z =
(4*2 + 1*5 + 9*1) (4*9 + 1*2 + 9*0)
(6*2 + 2*5 + 8*1) (6*9 + 2*2 + 8*0)
(7*2 + 3*5 + 5*1) (7*9 + 3*2 + 5*0)
Z =
22 38
30 58
34 69
然后只有这个打印语句:
C * D:
|22 38|
|30 58|
|34 69|
我需要使用其他树(或三个?不知道是否有错字)功能。在过去的三天里,我一直在尝试这个,并且查看了我能想到的所有内容。这是我尝试过的一些失败的代码(我只是注释掉出了问题的东西):
def matrixMUL(A,B):
Z = []
Z.append(int(dotProduct(row(A,B),col(A,B))))
#if len(col(B,j)) != len(row(A,i)):
#print("Cannot multiply the two matrices. Incorrect dimensions.")
#else:
#for n in range(row(A,i)):
#for m in range(col(B,j)):
#Z.append(dotProduct(x,y))
return Z
#mult = sum(p*q for p,q in zip(x,y))
#Z.append(mult)
#Z = []
#for i in range(len(A)):
#row = []
#for j in range(len(A[0])):
#row.append(A[i][j]+B[i][j])
#Z.append(row)
#return Z
我不知道我还能尝试什么。有人可以帮忙吗?