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 of shape and of shape , the result has shape :
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 is and is , then is .
Non-Commutativity
in general. Order matters.
Your Task
Implement mat_mul(A, B) that returns the matrix product as a list of lists.
Pyodide loading...
Loading...
Click "Run" to execute your code.