需要矩阵乘法辅助

问题描述 投票:0回答:1

因此,我具有这三个完整的函数,它们返回矩阵的所需行,矩阵的列以及行和列的点积,并且我需要以某种方式将它们网格化在一起以找到乘积两个矩阵相乘在一起。有什么建议吗?

#Test matrices
A = [[2,4], [7,0], [6,3]]
B = [[3,1], [-1,8], [-3, 3]]
C = [[4,1,9], [6,2,8], [7,3,5]]
D = [[2,9], [5,2], [1,0]]

def row(A,i):
    Z = []
    Z.append(A[i])
    return Z[0]


def col(B,j):
    Z=[]
    for i in range(len(B)):
        Z.append(B[i][j])
    return Z

def dotProduct(x,y):
    prod=0
    for i in range(len(x)):
        prod=prod+x[i]*y[i]
    return prod

def matrixMUL(A, B):
    Z = []
    ....
    return Z
python-3.x user-defined-functions matrix-multiplication dot-product
1个回答
0
投票

具有3个辅助功能的解决方案:

from functools import partial


#Test matrices

A = [[2,4], [7,0], [6,3]]
B = [[3,1], [-1,8], [-3, 3]]
C = [[4,1,9], [6,2,8], [7,3,5]]
D = [[2,9], [5,2], [1,0]]

def row(A,i):
    Z = []
    Z.append(A[i])
    return Z[0]

def col(B,j):
    Z=[]
    for i in range(len(B)):
        Z.append(B[i][j])
    return Z

def dotProduct(x,y):
    prod=0
    for i in range(len(x)):
        prod=prod+x[i]*y[i]
    return prod

def shape(A):
    num_rows = len(A)
    num_cols = len(A[0]) if A else 0
    return num_rows, num_cols

def matrix_product_entry(A, B, i, j):
    return dotProduct(row(A, i), col(B, j))

def matrix_make(rows, cols, entry_fn):
    return [[entry_fn(i, j) for j in range(cols)]
            for i in range(rows)]

def matrixMUL(A, B):
    n1, k1 = shape(A)
    print(n1, k1)
    n2, k2 = shape(B)
    if k1 != n2:
        raise ArithmeticError("matrices shapes are not compatible!")
    return matrix_make(n1, k2, partial(matrix_product_entry, A, B))

print (matrixMUL(C, D))
# returns [[22, 38], [30, 58], [34, 69]]
© www.soinside.com 2019 - 2024. All rights reserved.