Search code examples
pythonmatrixmultiplication

Matrix Multiplication Python - Matrix rows not seperated


I am currently trying to do matrix mult on python and the correct answer is appearing but, instead of each row being on it's own, all the rows are combined into one row then repeated for the number of rows.

def matrixtranspose(m1):
    mT = [[m1[i][x] for i in range(len(m1))] for x in range(len(m1[0]))]
    return mT

def dotProduct(m1row, m2column):
    l3 = [m1row[i] * m2column[i] for i in range(len(m1row))]
    dP = sum(l3)
    return dP

def matrixmult(m1, m2):
    transposedMatrix = matrixtranspose(m2)
    numRows = len(transposedMatrix)
    newMatrix = []
    addedDP = []

    for rows in range(0, (len(m1))):
            for col in range(0, len(transposedMatrix)):
                addedDP.append(dotProduct(m1[rows], transposedMatrix[col]))
            newMatrix.append(addedDP)

    return newMatrix

this will return:

[[4, 20, 4, 4, 20, 4, 6, 36, 6],
 [4, 20, 4, 4, 20, 4, 6, 36, 6],
 [4, 20, 4, 4, 20, 4, 6, 36, 6]]

Instead of:

[[4, 20, 4] [4, 20, 4] [6, 36, 6]]

how could I fix it?


Solution

  • The problem is in your accretion logic:

    addedDP = []
    
    for row in range(0, (len(m1))):
        for col in range(0, len(transposedMatrix)):
            addedDP.append(dotProduct(m1[row], transposedMatrix[col]))
    

    You are adding each element to addedDP as you go through the matrix: each product is appended to a global list of values, rather than only the values for the current row. addedDP doesn't reset for each new row. And then, for each row in the matrix:

        newMatrix.append(addedDP)
    

    you add the original reference to the entire list. Thus, when you finish, you have len(m1) copies of that list in your "result" list.

    You can fix this by re-initializing addedDP for each row:

    newMatrix = []
    
    for row in range(0, (len(m1))):
        addedDP = []
        for col in range(0, len(transposedMatrix)):
            addedDP.append(dotProduct(m1[row], transposedMatrix[col]))
            # print("row, col:", row, col, addedDP)
        newMatrix.append(addedDP)
        # print("row", row, addedDP)
    
    return newMatrix
    

    I left in my debugging print statements. I strongly recommend you learn this basic debugging tool: if you have an ailing program, ask it where things hurt! :-) See this lovely debug blog for help.

    Given a main program of:

    m1 = [[1, 2],
          [3, 4]]
    m2 = [[0, 1],
          [-1, 0]]
    print(matrixmult(m1, m2))
    

    Output with print statements enabled:

    row, col: 0 0 [-2]
    row, col: 0 1 [-2, 1]
    row 0 [-2, 1]
    row, col: 1 0 [-4]
    row, col: 1 1 [-4, 3]
    row 1 [-4, 3]
    [[-2, 1], [-4, 3]]