简体   繁体   English

该函数接受两个矩阵作为输入,并返回一个A * B的矩阵。在Python中

[英]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.

相关问题 编写一个名为 operations 的函数,将两个正整数 h 和 w 作为输入,生成两个大小为 hxw 的随机矩阵 A 和 B - Write a function called operations that takes as input two positive integers h and w, makes two random matrices A and B, of size h x w 编写一个 function,它将一个矩阵和一个标量乘数作为输入,并返回一个包含标量和矩阵的标量积的新矩阵 - Write a function that takes a matrix and a scalar multiplier as input and returns a new matrix containing the scalar product of the scalar and matrix Python function 接受两个函数并返回串联的 function? - Python function that takes two functions and returns the concatenated function? 如何在 C 中编写 function ,它将两个矩阵作为 numpy 数组作为输入 - How to write a function in C which takes as input two matrices as numpy array 如何在python中将一个矩阵分为两个矩阵? - how to divide one matrix into two matrices in python? 给定两个矩阵和一个采用两个向量的函数,如何对矩阵中每对向量的函数均值进行向量化? - Given two matrices and a function that takes two vectors, how to vectorize mean of function for every pair of vectors from the matrices? Numpy-在Python中创建一个输入为两个矩阵且输出为二进制矩阵的函数 - Numpy - Creating a function whose inputs are two matrices and whose output is a binary matrix in Python 找到以矩阵为输入的 Function 的最小值 - Find Minimum Of Function That Takes Matrix As Input python中的矩阵矩阵 - Matrix of matrices in python 如何在python中合并两个稀疏的coo_matrix矩阵? - How to merge two sparse coo_matrix matrices in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM