Skip to content
Easy Framework

Matrix Multiplication

Multiply two matrices by taking a dot product between each row of A and each column of B.

Your task

Implement matmul(A, B) using the framework's built-in matrix multiplication. A has shape (m, k) and B has shape (k, n). Both are floating-point tensors with the same dtype and device. Return shape (m, n), preserving dtype and device and leaving the inputs unchanged.

output[i, j] = sum(A[i, t] * B[t, j] for t from 0 to k-1)

For A=[[1, 2], [3, 4]] and B=[[5, 6], [7, 8]], return [[19, 22], [43, 50]]. The top-left value is 1*5 + 2*7 = 19: A's first row is paired with B's first column.

The shared inner dimension k is summed over. The remaining dimensions m and n become the output rows and columns. Matrices need not be square: (2, 3) multiplied by (3, 4) produces (2, 4).

Use A @ B, torch.matmul(A, B) or jnp.matmul(A, B). A * B is elementwise multiplication and does not compute these row-column sums. Keep the input order; B @ A may have a different result or incompatible shapes. Keep a matrix result even when m or n is 1.