Numpy - Matrix Operations
NumPy provides many functions for performing matrix operations, such as matrix multiplication, determinant, inverse, and rank.
To perform matrix multiplication, you can use the dot
function, which takes two arrays as arguments and returns their dot product. For example:
import numpy as np
# Create two 2x2 matrices
x = np.array([[1, 2], [3, 4]])
y = np.array([[5, 6], [7, 8]])
# Multiply the matrices
z = np.dot(x, y)
print(z) # [[19 22]
# [43 50]]
To compute the determinant of a matrix, you can use the linalg.det
function from NumPy's linalg
module, which takes an array and returns its determinant. For example:
import numpy.linalg as la
# Compute the determinant of a 2x2 matrix
x = np.array([[1, 2], [3, 4]])
determinant = la.det(x)
print(determinant) # -2.0
To compute the inverse of a matrix, you can use the linalg.inv
function from NumPy's linalg
module, which takes an array and returns its inverse. For example:
# Compute the inverse of a 2x2 matrix
x = np.array([[1, 2], [3, 4]])
inverse = la.inv(x)
print(inverse) # [[-2. 1. ]
# [ 1.5 -0.5]]
To compute the rank of a matrix, you can use the linalg.matrix_rank
function from NumPy's linalg
module, which takes an array and returns its rank. For example:
# Compute the rank of a 2x2 matrix
x = np.array([[1, 2], [3, 4]])
rank = la.matrix_rank(x)
print(rank) # 2