Home »
Python »
Python Programs
Python - Matrix Operations with SciPy
By IncludeHelp Last updated : September 14, 2024
Python SciPy provides various methods for performing different matrix operations.
Let us understand some examples of matrix operations using SciPy:
Example 1: Matrix Inversion
To find the matrix inversion, we can use the inv() method of scipy.linalg package.
# Import numpy
import numpy as np
# Import inv function from scipy
from scipy.linalg import inv
# Creating an array
arr = np.array([[1, 2], [3, 4]])
# Display original array
print("Original array:\n", arr, "\n")
# Finding inverse of array
arr_inv = inv(arr)
# Display result
print("Inverse matrix:\n", arr_inv)
Output
Original array:
[[1 2]
[3 4]]
Inverse matrix:
[[-2. 1. ]
[ 1.5 -0.5]]
Example 2: Solving Linear Systems
Use solve() method of scipy.linalg module to solve a system of linear equations. This method takes two input matrices and convert them into a system of linear equation.
# Import numpy
import numpy as np
# Import solve function from scipy
from scipy.linalg import solve
# Creating square matrix
arr1 = np.array([[3, 2, 0], [1, -1, 0], [0, 5, 1]])
# Creating right-hand side vector
arr2 = np.array([2, 4, -1])
# Display square matrix
print("Square matrix:\n", arr1, "\n")
# Display right-hand side vector
print("Right-hand side vector:\n", arr2, "\n")
# Solving linear equations (represented by arrays)
res = solve(arr1, arr2)
# Display result
print("Result:\n", res)
Output
Square matrix:
[[ 3 2 0]
[ 1 -1 0]
[ 0 5 1]]
Right-hand side vector:
[ 2 4 -1]
Result:
[ 2. -2. 9.]
Example 3: Constructing Sparse Matrices
To create sparse matrix, we can use csr_matrix() method from scipy.sparse module. The sparse csr matrix can be created in the following ways:
- As a dense matrix
- With another sparse matrix
- As empty matrix
- With data, row_indices and column_indices
- With data, indices, Indptr and shape attributes
Let us see how we can create a sparse csr matrix using data, indices of rows, and indices of columns.
# Import numpy
import numpy as np
# Import csr_matrix function
from scipy.sparse import csr_matrix
# Defining the data, row, and column
data = np.array([1, 2, 3, 4])
row = np.array([0, 0, 1, 2])
col = np.array([0, 2, 2, 0])
# Defining the shape of the matrix
shape = (3, 3)
# Creating the CSR matrix
csr = csr_matrix((data, (row, col)), shape).toarray()
# Display created csr matrix
print("Created CSR matrix:\n", csr)
Output
Created CSR matrix:
[[1 0 2]
[0 0 3]
[4 0 0]]
Python SciPy Programs »