NumPy – Matrix Multiplication
Matrix multiplication is one of the most important operations in:
- Machine learning
- Data science
- Computer graphics
- Neural networks
- Scientific computing
In Python, we use NumPy to perform matrix multiplication efficiently without writing complex loops.
What is Matrix Multiplication?
Matrix multiplication is a mathematical operation where rows of the first matrix are multiplied with columns of the second matrix.
Unlike addition or subtraction, it is not element-wise.
Rule of Matrix Multiplication
Two matrices A and B can be multiplied only if:
Columns of A = Rows of B
If:
- A is (m × n)
- B is (n × p)
Then:
- Result is (m × p)
Mathematical Representation
If:
A =
[ a11 a12 ]
[ a21 a22 ]
B =
[ b11 b12 ]
[ b21 b22 ]
Then:
A × B =
[ a11*b11 + a12*b21 a11*b12 + a12*b22 ]
[ a21*b11 + a22*b21 a21*b12 + a22*b22 ]
NumPy Installation
pip install numpy
Import NumPy
import numpy as np
1. Matrix Multiplication using @ Operator
The easiest and modern way:
import numpy as np
A = np.array([[1, 2],
[3, 4]])
B = np.array([[5, 6],
[7, 8]])
result = A @ B
print(result)
Output:
[[19 22]
[43 50]]
2. Using np.dot() Function
import numpy as np
A = np.array([[1, 2],
[3, 4]])
B = np.array([[5, 6],
[7, 8]])
result = np.dot(A, B)
print(result)
Output:
[[19 22]
[43 50]]
3. Using np.matmul() Function
import numpy as np
A = np.array([[2, 3],
[4, 5]])
B = np.array([[6, 7],
[8, 9]])
result = np.matmul(A, B)
print(result)
Output:
[[36 41]
[64 73]]
4. Matrix Multiplication with Different Shapes
import numpy as np
A = np.array([[1, 2, 3],
[4, 5, 6]])
B = np.array([[7, 8],
[9, 10],
[11, 12]])
result = A @ B
print(result)
Output:
[[ 58 64]
[139 154]]
Important Difference: * vs Matrix Multiplication
❌ Element-wise multiplication:
A * B
✅ Matrix multiplication:
A @ B
5. Common Error (Shape Mismatch)
ValueError: matmul: Input operand has incompatible dimensions
Solution:
Ensure:
- Columns of first matrix = Rows of second matrix
Real-World Applications
Matrix multiplication is used in:
1. Machine Learning
- Neural network layers
- Weight calculations
2. Computer Graphics
- 3D transformations
- Rotation and scaling
3. Data Science
- Feature transformations
- Dataset modeling
4. Physics & Engineering
- Simulations
- Signal processing
Why NumPy is Best for Matrix Multiplication?
- Extremely fast (C optimized)
- Simple syntax
- Handles large datasets
- Supports multi-dimensional arrays
- Industry standard in AI/ML
Summary
Matrix multiplication is a core concept in linear algebra and computing.
With NumPy, you can perform it easily using:
-
@operator -
np.dot() -
np.matmul()
All methods are optimized for performance in Python.
Conclusion
NumPy matrix multiplication is essential for anyone working in AI, data science, or engineering. It simplifies complex mathematical operations into clean, readable code.
Mastering this will significantly improve your understanding of numerical computing and machine learning workflows.


0 Comments