![]() |
VOOZH | about |
Given two matrices, the task is to multiply them together to form a new matrix. Each element in the result is obtained by multiplying the corresponding elements of a row from the first matrix and a column from the second matrix. For Example:
Input: A = [[1, 2], [3, 4]], B = [[5, 6], [7, 8]]
Output: [[19, 22], [43, 50]]
Explanation: 1×5 + 2×7 = 19,
1×6 + 2×8 = 22,
3×5 + 4×7 = 43,
3×6 + 4×8 = 50
Let's explore different methods to multiply two matrices in Python.
NumPy handles matrix multiplication internally using optimized C-based operations. It takes the rows of matrix A and the columns of matrix B, performs vectorized dot-products, and produces the result efficiently without manual loops.
[114 160 60 27] [74 97 73 14] [119 157 112 23]
Explanation: np.dot(A, B) computes all row × column dot-products internally using vectorized, compiled code.
This method first converts matrix B into its transpose so that its columns become easy to iterate. Then each row of A is multiplied with each column of the transposed B, forming each cell of the result through a clean and efficient dot-product.
[114, 160, 60, 27] [74, 97, 73, 14] [119, 157, 112, 23]
Explanation:
This method computes each result cell by pairing elements of a row from A with elements of a column from B (using zip(*B)), multiplying them, and summing the products. Everything is done in a single nested list comprehension, making it concise.
[114, 160, 60, 27] [74, 97, 73, 14] [119, 157, 112, 23]
Explanation:
This method uses the classic three-loop approach: the outer loop picks a row from A, the middle loop picks a column from B, and the inner loop multiplies corresponding elements and adds them up. It directly follows the mathematical definition of matrix multiplication.
[114, 160, 60, 27] [74, 97, 73, 14] [119, 157, 112, 23]
Explanation: