
- SciPy - Home
- SciPy - Introduction
- SciPy - Environment Setup
- SciPy - Basic Functionality
- SciPy - Relationship with NumPy
- SciPy Clusters
- SciPy - Clusters
- SciPy - Hierarchical Clustering
- SciPy - K-means Clustering
- SciPy - Distance Metrics
- SciPy Constants
- SciPy - Constants
- SciPy - Mathematical Constants
- SciPy - Physical Constants
- SciPy - Unit Conversion
- SciPy - Astronomical Constants
- SciPy - Fourier Transforms
- SciPy - FFTpack
- SciPy - Discrete Fourier Transform (DFT)
- SciPy - Fast Fourier Transform (FFT)
- SciPy Integration Equations
- SciPy - Integrate Module
- SciPy - Single Integration
- SciPy - Double Integration
- SciPy - Triple Integration
- SciPy - Multiple Integration
- SciPy Differential Equations
- SciPy - Differential Equations
- SciPy - Integration of Stochastic Differential Equations
- SciPy - Integration of Ordinary Differential Equations
- SciPy - Discontinuous Functions
- SciPy - Oscillatory Functions
- SciPy - Partial Differential Equations
- SciPy Interpolation
- SciPy - Interpolate
- SciPy - Linear 1-D Interpolation
- SciPy - Polynomial 1-D Interpolation
- SciPy - Spline 1-D Interpolation
- SciPy - Grid Data Multi-Dimensional Interpolation
- SciPy - RBF Multi-Dimensional Interpolation
- SciPy - Polynomial & Spline Interpolation
- SciPy Curve Fitting
- SciPy - Curve Fitting
- SciPy - Linear Curve Fitting
- SciPy - Non-Linear Curve Fitting
- SciPy - Input & Output
- SciPy - Input & Output
- SciPy - Reading & Writing Files
- SciPy - Working with Different File Formats
- SciPy - Efficient Data Storage with HDF5
- SciPy - Data Serialization
- SciPy Linear Algebra
- SciPy - Linalg
- SciPy - Matrix Creation & Basic Operations
- SciPy - Matrix LU Decomposition
- SciPy - Matrix QU Decomposition
- SciPy - Singular Value Decomposition
- SciPy - Cholesky Decomposition
- SciPy - Solving Linear Systems
- SciPy - Eigenvalues & Eigenvectors
- SciPy Image Processing
- SciPy - Ndimage
- SciPy - Reading & Writing Images
- SciPy - Image Transformation
- SciPy - Filtering & Edge Detection
- SciPy - Top Hat Filters
- SciPy - Morphological Filters
- SciPy - Low Pass Filters
- SciPy - High Pass Filters
- SciPy - Bilateral Filter
- SciPy - Median Filter
- SciPy - Non - Linear Filters in Image Processing
- SciPy - High Boost Filter
- SciPy - Laplacian Filter
- SciPy - Morphological Operations
- SciPy - Image Segmentation
- SciPy - Thresholding in Image Segmentation
- SciPy - Region-Based Segmentation
- SciPy - Connected Component Labeling
- SciPy Optimize
- SciPy - Optimize
- SciPy - Special Matrices & Functions
- SciPy - Unconstrained Optimization
- SciPy - Constrained Optimization
- SciPy - Matrix Norms
- SciPy - Sparse Matrix
- SciPy - Frobenius Norm
- SciPy - Spectral Norm
- SciPy Condition Numbers
- SciPy - Condition Numbers
- SciPy - Linear Least Squares
- SciPy - Non-Linear Least Squares
- SciPy - Finding Roots of Scalar Functions
- SciPy - Finding Roots of Multivariate Functions
- SciPy - Signal Processing
- SciPy - Signal Filtering & Smoothing
- SciPy - Short-Time Fourier Transform
- SciPy - Wavelet Transform
- SciPy - Continuous Wavelet Transform
- SciPy - Discrete Wavelet Transform
- SciPy - Wavelet Packet Transform
- SciPy - Multi-Resolution Analysis
- SciPy - Stationary Wavelet Transform
- SciPy - Statistical Functions
- SciPy - Stats
- SciPy - Descriptive Statistics
- SciPy - Continuous Probability Distributions
- SciPy - Discrete Probability Distributions
- SciPy - Statistical Tests & Inference
- SciPy - Generating Random Samples
- SciPy - Kaplan-Meier Estimator Survival Analysis
- SciPy - Cox Proportional Hazards Model Survival Analysis
- SciPy Spatial Data
- SciPy - Spatial
- SciPy - Special Functions
- SciPy - Special Package
- SciPy Advanced Topics
- SciPy - CSGraph
- SciPy - ODR
- SciPy Useful Resources
- SciPy - Reference
- SciPy - Quick Guide
- SciPy - Cheatsheet
- SciPy - Useful Resources
- SciPy - Discussion
SciPy - Matrix Creation & Basic Operations
SciPy offers many convenient functions for creating and manipulating matrices by extending the capabilities of NumPy. The scipy.linalg module in SciPy provides functions for creating and performing basic operations on matrices such as linear algebraic computations like solving systems of linear equations, finding determinants and performing matrix factorization.
It is similar to the NumPy library but SciPys linalg module extends NumPys capabilities with more advanced linear algebra tools.
In this chapter let's discuss in detail about the matrix creation and basic operations using scipy.linalg −
Creating a Matrix in SciPy
Matrix creation in SciPy and NumPy involves using a variety of functions to initialize matrices with different values, structures and properties. Here are various ways to create matrices in SciPy which focus on common techniques, special matrices and properties −
To create matrices SciPy uses the same array creation techniques as NumPy with an additional focus on linear algebra functions. Here is the example of it −
import numpy as np import scipy.linalg as la # Creating a matrix (2x2) A = np.array([[1, 2], [3, 4]]) print("The 2x2 matrix:",A) # Creating a square matrix of zeros (3x3) B = np.zeros((3, 3)) print("The 3x3 square matrix:,"B) # Creating an identity matrix (4x4) I = np.eye(4) print("The 4X4 Identity matrix:,"I) # Creating a random matrix R = np.random.rand(3, 3) print("The Random matrix:,"R)
Following is the output of creating the different type of matrices −
The 2x2 matrix: [[1 2] [3 4]] The 3x3 square matrix: [[0. 0. 0.] [0. 0. 0.] [0. 0. 0.]] The 4X4 Identity matrix: [[1. 0. 0. 0.] [0. 1. 0. 0.] [0. 0. 1. 0.] [0. 0. 0. 1.]] The Random matrix: [[0.93209861 0.44003913 0.94137284] [0.25650407 0.59441862 0.49890997] [0.65446923 0.38596346 0.92084365]]
Basic Matrix Operations in SciPy
scipy.linalg supports numerous matrix operations such as addition, subtraction, multiplication, transpose, etc. Some functions are more efficient than using basic NumPy operations.
Matrix Multiplication
Scipy does not have functions to perform the matrix multiplication, in such case we can use the numpy library np.matmul() function. Following is the example of performing the matrix multiplication using np.matmul() and @ decorator −
import numpy as np # Define matrices A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]]) import scipy.linalg as la # Matrix multiplication F = A @ B # Using @ operator G = np.matmul(A, B) # Using np.matmul print("Matrix Multiplication using @:\n", F) print("Matrix Multiplication using np.matmul:\n", G)
Following is the output of matrix multiplication performed using @ and np.transpose() −
Matrix Multiplication using @: [[19 22] [43 50]] Matrix Multiplication using np.matmul: [[19 22] [43 50]]
Matrix Transpose in SciPy
Since scipy.linalg module doesnt provide a direct transpose function its common to use numpy.transpose() or the .T attribute for this operation. Both approaches are efficient and work well with scipy for other matrix operations if we need them. Following is the example of performing matrix transpose −
import numpy as np A = np.array([[1, 2], [3, 4]]) A_transpose = A.T print("Matrix transpose using .T",A_transpose) transpose_matrix = np.transpose(A) print("Matrix transpose using transpose()",transpose_matrix)
Following is the output of Performing matrix transpose using numpy −
Matrix transpose using .T [[1 3] [2 4]] Matrix transpose using transpose() [[1 3] [2 4]]
Matrix Addition and Subtraction in SciPy
Matrix addition and subtraction are not directly available in scipy.linalg either as these are basic operations typically handled by numpy. However we can use scipy in combination with numpy to perform these operations. Below is the example which shows how to perform matrix addition and subtraction using numpy −
import numpy as np A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]]) # Matrix addition C_add = A + B print("Addition:\n", C_add) # Matrix subtraction C_subtract = A - B print("Subtraction:\n", C_subtract)
Following is the output of Performing matrix addition and subtraction using numpy −
Addition: [[ 6 8] [10 12]] Subtraction: [[-4 -4] [-4 -4]]
Element wise Matrix Multiplication in SciPy
Element-wise multiplication in Python can be easily done with numpy using either the * operator or numpy.multiply. While scipy.linalg does not provide a specific function for element-wise multiplication we can still use numpy alongside scipy. Here is the example of it −
import numpy as np A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]]) # Element-wise multiplication C = A * B print("Element-wise Multiplication using *:\n", C) D = np.multiply(A, B) print("Element-wise Multiplication using multiply():\n", D)
Following is the output of Performing matrix element wise multiplication −
Element-wise Multiplication using *: [[ 5 12] [21 32]] Element-wise Multiplication using multiply(): [[ 5 12] [21 32]]
Matrix Inversion in SciPy
Matrix inversion is the process of finding a matrix that, when multiplied by the original matrix, yields the identity matrix. In scipy.linalg matrix inversion can be done using the scipy.linalg.inv() function.
Following are the key points to be considered while performing inversion of the matrix −
- scipy.linalg.inv(A) computes the inverse of matrix A.
- The matrix must be square i.e., it has the same number of rows and columns and non-singular i.e., it must have a non-zero determinant.
- After computing the inverse we can verify the result by multiplying the original matrix with its inverse which should yield the identity matrix.
Check for Singular Matrix
We can check the determinant using np.linalg.det(A) or scipy.linalg.det(A) to finrd whether the given matrix is singular or not. If the matrix is singular then it has a determinant of 0 and the inversion will fail and we will get an error or a warning. Here is the example which checks for the singular matrix −
import numpy as np from scipy import linalg # Define a square matrix A = np.array([[1, 2], [3, 4]]) if linalg.det(A) == 0: print("Matrix is singular, so it doesn't have an inverse.") else: A_inv = linalg.inv(A) print("Inverse of A:", A_inv)
Following is the output which checks whether the given matrix is singular or not −
Inverse of A: [[-2. 1. ] [ 1.5 -0.5]]
Here is the example which shows how we can perform matrix inversion using scipy.linalg.inv() −
import numpy as np from scipy import linalg # Define a square matrix A = np.array([[1, 2], [3, 4]]) # Compute the inverse using scipy.linalg.inv A_inv = linalg.inv(A) print("Matrix A:") print(A) print("\nInverse of A:") print(A_inv) # To verify the result, multiply the matrix with its inverse and check if it gives the identity matrix identity_matrix = np.dot(A, A_inv) print("\nA * A_inv (should be identity matrix):") print(identity_matrix)
Following is the output of Performing matrix inversion using the scipy.linalg.inv() −
Inverse of A: [[-2. 1. ] [ 1.5 -0.5]] PS D:\Tutorialspoint> python sample.py Matrix A: [[1 2] [3 4]] Inverse of A: [[-2. 1. ] [ 1.5 -0.5]] A * A_inv (should be identity matrix): [[1.0000000e+00 0.0000000e+00] [8.8817842e-16 1.0000000e+00]]
Matrix Determinant in SciPy
The determinant of a square matrix is a scalar value that provides significant information about the matrix. In linear algebra the determinant can be used to answer questions about the invertibility of a matrix among other things.
In this example to compute the determinant of a matrix we are using SciPy where we can use the function scipy.linalg.det() −
import numpy as np from scipy import linalg # Define a square matrix A = np.array([[1, 2], [3, 4]]) # Compute the determinant using scipy.linalg.det det_A = linalg.det(A) print("Matrix A:") print(A) print("\nDeterminant of A:") print(det_A)
Following is the output of Performing matrix determinant using the scipy.linalg.det() −
Matrix A: [[1 2] [3 4]] Determinant of A: -2.0