简体   繁体   English

没有 Numpy 的广义矩阵乘法

[英]Generalized Matrix Multiplication without Numpy

I want to make a system that allows me to input 2 matrixes, and it output a correct answer.我想制作一个允许我输入 2 个矩阵的系统,它 output 是正确答案。 I've gotten it to work with specifically a 1 x 3 * 3 x 2. But I want to make it more open ended.我已经让它专门用于 1 x 3 * 3 x 2。但我想让它更开放。 How could I do this?我怎么能这样做?

# 1 x 3 by 3 x 2
def matmul(matA, matB):

    p1 = matA[0][0] * matB[0][0]
    p2 = matA[1][0] * matB[2][0]
    p3 = matA[2][0] * matB[4][0]
    
    num1 = p1 + p2 + p3
    
    p1 = matA[0][0] * matB[1][0]
    p2 = matA[1][0] * matB[3][0]
    p3 = matA[2][0] * matB[5][0]
    
    num2 = p1 + p2 + p3

    # Output is a 1 x 2 Matrix
    result = [num1, num2]
    print(result)

# ----------------------------------- #

# 1 x 3 Matrix
A = (
 [5],
 [-5],
 [10]
)

# 3 x 2 Matrix
B = (
 [-10], [13],
 [57], [-37],
 [-96], [15]
)

# Outputs a 1 x 2 Matrix
MatMult(A, B)

I expect that you will find many example of this, but here is working code.我希望你会找到很多这样的例子,但这里是工作代码。 In particular, you will use nested for loops or nested list comprehension to generate the final matrix.特别是,您将使用nested for loopsnested list comprehension来生成最终矩阵。

# Program to multiply two matrices using nested loops

# 3x3 matrix
X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
    [6,7,3,0],
    [4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
         [0,0,0,0],
         [0,0,0,0]]

# iterate through rows of X
for i in range(len(X)):
   # iterate through columns of Y
   for j in range(len(Y[0])):
       # iterate through rows of Y
       for k in range(len(Y)):
           result[i][j] += X[i][k] * Y[k][j]

for r in result:
   print(r)

And here is an example of the same: https://www.programiz.com/python-programming/examples/multiply-matrix这是一个相同的例子: https://www.programiz.com/python-programming/examples/multiply-matrix

# 1 x 3 Matrix
A = [ [5, -5, 10]]

# 3 x 2 Matrix
B = [
 [-10, 13],
 [57, -37],
 [-96, 15]
]

def mult_matx(A, B):
    
    rowsA = len(A)
    colsB = len(B[0])
    result = [[0] * colsB for i in range(rowsA)]
    
    for i in range(rowsA):
        
        # iterating by column by B
        for j in range(colsB):
            
            
            # iterating by rows of B
            for k in range(len(B)):
                
                result[i][j] += A[i][k] * B[k][j]
 
    for r in result:
        print(r)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM