What Is Linear Algebra in NumPy?

Linear algebra deals with vectors, matrices, and mathematical operations on them. NumPy provides a powerful submodule called numpy.linalg that supports efficient and accurate linear algebra computations.

These functions are widely used in data science, machine learning, physics, engineering, and computer graphics.

Why Use NumPy for Linear Algebra?

NumPy linear algebra:

  • Works efficiently with large matrices

  • Uses optimized low-level libraries (BLAS/LAPACK)

  • Supports multi-dimensional arrays

  • Is faster and more accurate than manual calculations

  • Integrates well with scientific workflows

Creating Vectors and Matrices

Python
import numpy as np vector = np.array([1, 2, 3]) matrix = np.array([[1, 2], [3, 4]]) print(vector) print(matrix) # Output: # [1 2 3] # [[1 2] # [3 4]]

Matrix Addition & Subtraction

Python
A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]]) print(A + B) print(A - B) # Output: # [[ 6 8] # [10 12]] # [[-4 -4] # [-4 -4]]

Matrix Multiplication

Using @ Operator

Python
A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]]) print(A @ B) # Output: # [[19 22] # [43 50]]

Using dot()

Python
A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]]) print(np.dot(A,B) # Output: # [[19 22] # [43 50]]

Transpose of a Matrix

Python
import numpy as np
A = np.array([[1, 2], [3, 4]]) print(A.T) # Output: # [[1 2] # [3 4]]

Determinant

Python
import numpy as np
A = np.array([[1, 2], [3, 4]]) print(np.linalg.det(A)) # Output: # -2.0000000000000004

Inverse of a Matrix

Python
A = np.array([[1, 2], [3, 4]]) print(np.linalg.inv(A)) # Output: # [[-2. 1. ] # [ 1.5 -0.5]] 

Rank of a Matrix

print(np.linalg.matrix_rank(A)) # Output: # 2

Eigenvalues and Eigenvectors

Python
A = np.array([[1, 2], [3, 4]]) values, vectors = np.linalg.eig(A) 
print(values) 
print(vectors) 
# Output: 
# [-0.37228132 5.37228132] 
# [[-0.82456484 -0.41597356]
# [ 0.56576746 -0.90937671]]

Solving Linear Equations

Solve systems like:


Ax = b
Python
A = np.array([[2, 1], [1, 3]]) b = np.array([8, 13]) x = np.linalg.solve(A, b) print(x) # Output: # [3. 4.]

Common NumPy Linear Algebra Functions

FunctionPurpose
np.dot()Dot product
@Matrix multiplication
np.linalg.inv()Matrix inverse
np.linalg.det()Determinant
np.linalg.eig()Eigenvalues & vectors
np.linalg.solve()Solve linear equations
np.linalg.norm()Vector/matrix norm
np.linalg.matrix_rank()Matrix rank