Search code examples
pythonmatrix-multiplication

Generalized Matrix Multiplication without Numpy


I want to make a system that allows me to input 2 matrixes, and it output a correct answer. I've gotten it to work with specifically a 1 x 3 * 3 x 2. But I want to make it more open ended. 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)

Solution

  • # 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)