Python ModulesNumpy TutorialNumpy Linear Algebra

NumPy Linear Algebra

NumPy’s linear algebra module provides powerful tools for performing matrix operations, solving systems of equations, and working with eigenvalues and eigenvectors. These functions are essential for scientific computing, machine learning, and data analysis.


Matrix Operations

Matrix Multiplication

NumPy provides the dot() and matmul() functions for performing matrix multiplication.

import numpy as np
 
# Define matrices
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
 
# Dot product
result_dot = np.dot(matrix1, matrix2)
print("Dot Product:\n", result_dot)
 
# Matrix multiplication
result_matmul = np.matmul(matrix1, matrix2)
print("Matrix Multiplication:\n", result_matmul)

Output:

Dot Product:
 [[19 22]
  [43 50]]
Matrix Multiplication:
 [[19 22]
  [43 50]]

Determinants and Inverses

Determinant of a Matrix

The linalg.det() function computes the determinant of a matrix.

# Compute determinant
determinant = np.linalg.det(matrix1)
print("Determinant:", determinant)

Output:

Determinant: -2.0000000000000004

Inverse of a Matrix

The linalg.inv() function computes the inverse of a square matrix.

# Compute inverse
inverse = np.linalg.inv(matrix1)
print("Inverse:\n", inverse)

Output:

Inverse:
 [[-2.   1. ]
  [ 1.5 -0.5]]

Eigenvalues and Eigenvectors

The linalg.eig() function computes the eigenvalues and eigenvectors of a square matrix.

# Compute eigenvalues and eigenvectors
eigenvalues, eigenvectors = np.linalg.eig(matrix1)
print("Eigenvalues:", eigenvalues)
print("Eigenvectors:\n", eigenvectors)

Output:

Eigenvalues: [-0.37228132  5.37228132]
Eigenvectors:
 [[-0.82456484 -0.41597356]
  [ 0.56576746 -0.90937671]]

Try It Yourself

Problem 1: Matrix Multiplication

Create two 2D arrays and perform matrix multiplication using matmul().

Show Code
import numpy as np
 
# Define matrices
matrix1 = np.array([[2, 3], [1, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
 
# Perform matrix multiplication
result = np.matmul(matrix1, matrix2)
print("Matrix Multiplication:\n", result)

Problem 2: Compute Determinant and Inverse

Create a 2x2 matrix. Compute its determinant and inverse.

Show Code
import numpy as np
 
# Define a matrix
matrix = np.array([[3, 1], [2, 4]])
 
# Compute determinant
determinant = np.linalg.det(matrix)
print("Determinant:", determinant)
 
# Compute inverse
inverse = np.linalg.inv(matrix)
print("Inverse:\n", inverse)

Problem 3: Eigenvalues and Eigenvectors

Create a 2x2 matrix and compute its eigenvalues and eigenvectors.

Show Code
import numpy as np
 
# Define a matrix
matrix = np.array([[6, 2], [2, 3]])
 
# Compute eigenvalues and eigenvectors
eigenvalues, eigenvectors = np.linalg.eig(matrix)
print("Eigenvalues:", eigenvalues)
print("Eigenvectors:\n", eigenvectors)

Pyground

Play with Python!

Output: