[英]A function that takes two matrices as input, and returns a matrix with A * B. In Python
I am trying to figure out how to create a dot product matrix. 我试图弄清楚如何创建点积矩阵。 Here is the code I have made so far:
这是我到目前为止编写的代码:
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))
It's the matrixMUL(A,B)
part that I am having trouble with. 这是我遇到麻烦的
matrixMUL(A,B)
部分。 The program is supposed to go through this kind of calculation: Example: 该程序应该经过这种计算:示例:
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
and then have just this print statement: 然后只有这个打印语句:
C * D:
|22 38|
|30 58|
|34 69|
I NEED to use the other tree (or three? don't know if there is a typo or not) functions. 我需要使用另一棵树(或三棵树?不知道是否有错字)功能。 I've been trying this for the last three days and have looked up about everything I can think of.
在过去的三天里,我一直在尝试这种方法,并且对我能想到的一切进行了查找。 This is some of the code I have tried which have failed (I just comment out the stuff that went wrong):
这是我尝试过的一些失败的代码(我只是在注释出错的地方):
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
I don't know what else I can try. 我不知道我还能尝试什么。 Can someone help?
有人可以帮忙吗?
You can do it this way: 您可以这样操作:
def matrixMUL(A,B):
Z = [[0] * len(B[0]) for zz in range(len(A))]
for i in range(0,len(A)):
a = row(A,i)
for j in range(0,len(B[0])):
b = col(B,j)
Z[i][j] = sum(p*q for p,q in zip(a,b))
return Z
A difficulty that I've encountered when writing code like this is initialising the matrix correctly in the first place. 我在编写这样的代码时遇到的困难是首先正确地初始化矩阵。
If we use code like Z = [[0] * len(B[0])] * len(A)
, then we end up creating a list Z
that contains len(A)
references to the same list of length len(B[0])
zeros. 如果我们使用
Z = [[0] * len(B[0])] * len(A)
,则最终将创建一个列表Z
,其中包含对相同长度len(B[0])
len(A)
的列表的len(A)
引用。 len(B[0])
零。 Thus, code like z[0][0] = 1
will appear to "magically" change Z[1][0]
and Z[2][0]
to equal 1
at the same time, because all of these refer to the same element in the same list. 因此,类似
z[0][0] = 1
代码似乎会“神奇地”同时将Z[1][0]
和Z[2][0]
更改为等于1
,因为所有这些都引用了同一列表中的相同元素。
By initialising the matrix Z
with a list comprehension as shown above, we can be sure we have a set of unique lists referred to in Z
. 通过使用列表理解初始化矩阵
Z
,我们可以确定我们有一组在Z
中引用的唯一列表。
Another approach that avoids the need to initialise all of Z
(and thus avoids the list reference problem entirely) is: 另一种避免初始化所有
Z
(从而完全避免了列表引用问题)是:
def matrixMUL2(A,B):
Z = []
for i in range(0,len(A)):
a = row(A,i)
r = []
for j in range(0,len(B[0])):
b = col(B,j)
r.append(sum(p*q for p,q in zip(a,b)))
Z.append(r)
return Z
Neither function does as much error checking as it should (eg checking that the matrices have corresponding dimension sizes, as is required for multiplication), so they are not up to a good production-code standard as yet. 这两个函数都没有进行应有的错误检查(例如,检查矩阵是否具有相乘的尺寸,这是乘法所需要的),因此它们目前尚未达到良好的生产代码标准。 Also, as has been suggested in comments, if
numpy
was available, I'd highly recommend using numpy
instead of writing one's own code for this. 此外,正如在评论有人建议,如果
numpy
是可用的,我会强烈建议使用numpy
编写自己的代码它来代替。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.