Lesson 7 of 18

Matrix Multiplication

Matrix Multiplication

Matrix multiplication is not element-wise. Each entry of the result is a dot product of a row from the left matrix with a column from the right matrix.

For mathbfAmathbf{A} of shape (mimesn)(m imes n) and mathbfBmathbf{B} of shape (nimesp)(n imes p), the result mathbfCmathbf{C} has shape (mimesp)(m imes p):

Cij=sumk=1nAikcdotBkjC_{ij} = sum_{k=1}^{n} A_{ik} cdot B_{kj}

A = [[1, 2],
     [3, 4]]

B = [[5, 6],
     [7, 8]]

def mat_mul(A, B):
    m, n, p = len(A), len(A[0]), len(B[0])
    return [[sum(A[i][k] * B[k][j] for k in range(n))
             for j in range(p)]
            for i in range(m)]

print(mat_mul(A, B))
# [[1·5+2·7, 1·6+2·8],   [[19, 22],
#  [3·5+4·7, 3·6+4·8]] =  [43, 50]]

Shape Rule

The inner dimensions must match: if mathbfAmathbf{A} is (mimesn)(m imes n) and mathbfBmathbf{B} is (nimesp)(n imes p), then mathbfAmathbfBmathbf{A}mathbf{B} is (mimesp)(m imes p).

Non-Commutativity

mathbfAmathbfBeqmathbfBmathbfAmathbf{A}mathbf{B} eq mathbf{B}mathbf{A} in general. Order matters.

Your Task

Implement mat_mul(A, B) that returns the matrix product mathbfAmathbfBmathbf{A}mathbf{B} as a list of lists.

Pyodide loading...
Loading...
Click "Run" to execute your code.