Loading content...
Matrix multiplication is one of the most fundamental operations in linear algebra and serves as the backbone for countless algorithms in machine learning, computer graphics, physics simulations, and data science. When two matrices are multiplied together, the result encodes a composition of linear transformations, enabling complex multi-step transformations to be expressed as a single matrix operation.
Given two matrices A of dimensions n × m and B of dimensions p × q, the product C = A · B is defined only when the number of columns in A equals the number of rows in B (i.e., m = p). When this condition is satisfied, the resulting matrix C has dimensions n × q.
Each element C[i][j] of the resulting matrix is computed as the dot product of the i-th row of matrix A and the j-th column of matrix B:
$$C_{ij} = \sum_{k=1}^{m} A_{ik} \cdot B_{kj}$$
Dimensional Compatibility Rule:
Important Properties:
Your Task: Write a Python function that computes the product of two matrices. The function should:
a = [[1, 2], [2, 4]]
b = [[2, 1], [3, 4]][[8, 9], [16, 18]]Matrix A is 2×2 with 2 columns. Matrix B is 2×2 with 2 rows. Since columns(A) = rows(B) = 2, multiplication is valid.
The result is a 2×2 matrix computed as:
• C[0][0] = (1×2) + (2×3) = 2 + 6 = 8 • C[0][1] = (1×1) + (2×4) = 1 + 8 = 9 • C[1][0] = (2×2) + (4×3) = 4 + 12 = 16 • C[1][1] = (2×1) + (4×4) = 2 + 16 = 18
The resulting product matrix is [[8, 9], [16, 18]].
a = [[1, 2], [2, 4]]
b = [[2, 1], [3, 4], [4, 5]]-1Matrix A is 2×2 with 2 columns. Matrix B is 3×2 with 3 rows. Since columns(A) = 2 but rows(B) = 3, and 2 ≠ 3, the dimensions are incompatible for matrix multiplication. The function returns -1.
a = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
b = [[5, 6, 7], [8, 9, 10], [11, 12, 13]][[5, 6, 7], [8, 9, 10], [11, 12, 13]]Matrix A is the 3×3 identity matrix. The identity matrix has 1s on the main diagonal and 0s elsewhere. Multiplying any matrix by the identity matrix returns the original matrix unchanged.
• I · B = B (identity is the neutral element for matrix multiplication)
This demonstrates that the identity matrix preserves any matrix it multiplies, just as multiplying a number by 1 preserves that number.
Constraints