Matrix Operations in NumPy
Matrix operations are a core part of numerical computing, data science, and machine learning. NumPy provides fast and efficient tools to perform matrix calculations using arrays.
In this lesson, you will learn how to perform addition, subtraction, multiplication, and other matrix-level operations.
Understanding Matrices in NumPy
In NumPy, matrices are represented as 2D arrays. Each row represents a record, and each column represents a feature.
Let us start with two matrices containing numeric data.
Creating Sample Matrices
import numpy as np
A = np.array([[2, 4],
[6, 8]])
B = np.array([[1, 3],
[5, 7]])
print(A)
print(B)
Matrix A and B are both 2×2 matrices.
Matrix Addition
Matrix addition is performed element by element. Both matrices must have the same shape.
add_result = A + B
print(add_result)
Output:
[[ 3 7]
[11 15]]
Each element is added with its corresponding position.
Matrix Subtraction
Subtraction also happens element by element.
sub_result = A - B
print(sub_result)
Output:
[[1 1]
[1 1]]
Each value in matrix B is subtracted from matrix A.
Element-wise Multiplication
Using the * operator performs element-wise multiplication,
not matrix multiplication.
elementwise = A * B
print(elementwise)
Output:
[[ 2 12]
[30 56]]
Each element is multiplied with its corresponding element.
Matrix Multiplication
True matrix multiplication follows linear algebra rules
and is performed using @ or np.dot().
matrix_mul = A @ B
print(matrix_mul)
Output:
[[22 34]
[46 74]]
Rows from matrix A are multiplied with columns from matrix B.
Transpose of a Matrix
The transpose swaps rows and columns.
transpose_A = A.T
print(transpose_A)
Output:
[[2 6]
[4 8]]
Transposition is commonly used in data transformations and ML pipelines.
Matrix Determinant
The determinant helps understand matrix properties such as invertibility.
det = np.linalg.det(A)
print(det)
Output:
-8.0
A non-zero determinant means the matrix is invertible.
Matrix Inverse
The inverse matrix is used to solve linear equations.
inverse_A = np.linalg.inv(A)
print(inverse_A)
Output:
[[-1. 0.5]
[ 0.75 -0.25]]
Only square matrices with non-zero determinants can be inverted.
Real-World Use Case
Matrix operations are used in:
- Machine learning algorithms
- Linear regression and optimization
- Image transformations
- Scientific simulations
NumPy makes these operations fast and memory-efficient.
Practice Exercise
Task
- Create two 3×3 matrices
- Perform addition and subtraction
- Compute matrix multiplication
- Find transpose and determinant
What’s Next?
In the next lesson, you will learn about Linear Algebra in NumPy, where matrix operations are applied to solve equations.