![]()
The error message:
IndexError: matrix dimension mismatch
occurs when you try to perform operations on matrices (such as NumPy arrays or nested lists) where the dimensions do not align properly.
This typically happens in NumPy, Pandas, or nested lists, when:
- Accessing an element in a matrix with an incorrect index
- Performing operations (addition, multiplication) on matrices of different shapes
- Transposing or reshaping a matrix incorrectly
1. Causes and Solutions
Cause 1: Accessing an Index That Exceeds Matrix Dimensions
Trying to access an element with a row or column index that is out of bounds causes an IndexError.
Incorrect Code:
matrix = [[1, 2, 3],
[4, 5, 6]] # 2 rows × 3 columns
print(matrix[2][0]) # Error: Index 2 is out of bounds (only indices 0 and 1 exist)
Solution: Verify the index before accessing elements.
row, col = 2, 0
if 0 <= row < len(matrix) and 0 <= col < len(matrix[0]):
print(matrix[row][col])
else:
print("Index out of bounds")
Cause 2: Matrix Addition with Mismatched Dimensions
Matrix addition requires both matrices to have the same number of rows and columns.
Incorrect Code (NumPy):
import numpy as np
A = np.array([[1, 2],
[3, 4]]) # 2×2 matrix
B = np.array([[5, 6, 7],
[8, 9, 10]]) # 2×3 matrix
C = A + B # Error: Dimensions (2×2) and (2×3) do not match
Solution: Ensure both matrices have the same shape.
if A.shape == B.shape:
C = A + B
else:
print("Matrix dimensions do not match for addition")
Cause 3: Matrix Multiplication with Incorrect Shapes
Matrix multiplication follows the rule:
Number of columns in the first matrix must equal the number of rows in the second matrix.
Incorrect Code (NumPy):
import numpy as np
A = np.array([[1, 2],
[3, 4]]) # Shape: (2×2)
B = np.array([[5, 6],
[7, 8],
[9, 10]]) # Shape: (3×2)
C = np.dot(A, B) # Error: (2×2) cannot be multiplied with (3×2)
Solution: Check if the number of columns in A matches the number of rows in B.
if A.shape[1] == B.shape[0]:
C = np.dot(A, B)
else:
print("Matrix dimensions do not match for multiplication")
Cause 4: Incorrect Use of .reshape()
If you try to reshape a matrix into an incompatible shape, Python will raise an error.
Incorrect Code:
import numpy as np
A = np.array([[1, 2],
[3, 4]]) # Shape: (2×2)
A_reshaped = A.reshape(3, 2) # Error: Cannot reshape (2×2) into (3×2)
Solution: Ensure the total number of elements remains the same.
if A.size == 3 * 2:
A_reshaped = A.reshape(3, 2)
else:
print("Cannot reshape matrix due to dimension mismatch")
Cause 5: Indexing a Higher-Dimensional Array Incorrectly
If you attempt to access an element using too many indices, you will get a mismatch error.
Incorrect Code:
import numpy as np
A = np.array([[1, 2, 3],
[4, 5, 6]]) # 2D array
print(A[0, 0, 0]) # Error: Only 2 dimensions exist, but 3 indices are given
Solution: Use the correct number of indices.
print(A[0, 0]) # Accessing the first row, first column
