
- 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 - solve() Function
The scipy.linalg.solve() function is used to solve a system of linear equations of the form −
Ax = B
Where A is the square matrix (nn), constants of the system are represented in vector or matrix B that is in nm shape. The solution of the system is an unknown vector or matrix x.
The solve() method will raise ValueError if there are size discrepancies or the input matrix A is not square. If the matrix is singular (non-invertible), regardless of symmetry, it produces a LinAlgError. If the input matrix is complex and transposed=True, a NotImplementedError will occur; if the input matrix is ill-conditioned, a LinAlgWarning may be raised.
Syntax
Following is the syntax of the SciPy solve() method −
scipy.linalg.solve(a, b,lower=False, overwrite_a=False, overwrite_b=False, check_finite=True, assume_a='gen', transposed=False)
Parameters
Following are the parameters of solve() method
a (array_like, shape (n, n)) − Coefficient matrix A.
b array_like, shape (n,) or (n, k) − Input equation of Right-hand side.
lower (bool, optional) − If true the matrix uses the data only in the lower triangle of A, entries above the diagonal are ignored. If false the matrix uses the data in the upper triangle of A, entries below the diagonal are ignored. By default it is false.
overwrite_a (bool, optional) − If True, the input matrix A will be overwritten, which may save memory but can modify the original matrix. Default is False.
overwrite_b (bool, optional) − If True, the input matrix B will be overwritten. Default is False.
check_finite (bool, optional)− If True, it checks whether the A and B contain only valid numbers (no NaNs or Infs). Disabling this parameter will speed up the process if you are confident that the data is valid.
assume_a str, {'gen', 'sym', 'her', 'pos'}, optional, default 'gen' − To use a specialized solver for specific types of matrices we use assume_a parameter.
'gen': General matrix(default).
'sym': Symmetric matrix.
'her': Hermitian matrix.
'pos': Positive definite matrix.
transposed (bool, optional) − If True, solve for A^T x = b, assuming A is transposed. Default is false.
Return Value
x: ndarray, shape (n,) or (n, k). The solution to the system Ax = B, where x satisfies the equation.
Example 1: Solve Linear Equations with SciPy's solve()
In the below example we have created a Coefficient matrix A and Input data(right hand side of the equation) B. With the help of solve() method we will solve system of equation Ax = B. Result is the solution vector x.
import numpy as np from scipy.linalg import solve # Define a matrix A A = np.array([[2, 1], [5, 7]]) # Define a right-hand side matrix B B = np.array([11, 13]) # Solve for X such that AX = B x = solve(A, b) print("Solution x:", x)
When we run above the program, it produces the following result
Solution x: [ 7.11111111 -3.22222222]
Example 2: Optimize Symmetric Matrices using assume_a='sym'
We can use the assume_a='sym' parameter to optimize solving for symmetric coefficient matrices, which can be inverted if their determinant is non-zero.
In the below example, let us create a Symmetric matrix A and use the assume_a parameter to solve the equation. Following is the code −
import numpy as np from scipy.linalg import solve A = np.array([[4, 1], [1, 3]]) b = np.array([1, 2]) x = solve(A, b, assume_a='sym') print("Solution x:", x)
Following is an output of the above code
Solution x: [0.09090909 0.63636364]
Example 3: Verify Solutions with np.dot() and solve()
In the below code, we have inputs A, b and solve x using scipy.linalg.solve() for the equation Ax=b and verify the solution using np.dot() function.
import numpy as np from scipy import linalg A = np.array([[1, 2], [3, 4]]) b = np.array([5, 11]) x = linalg.solve(A, b) print("Solution x:", x) #verifying the solution print("Verification (A * x == b):", np.allclose(np.dot(A, x), b))
Output of the above code is as follows
Solution x: [1. 2.] Verification (A * x == b): True
Example 4: Solve Invertible Matrices with Non-Zero Determinants
Only if a square matrix has a non-zero determinant it can be inverted.
Construct a matrix A and find the determinant. If this determinant is zero, the matrix is invertible, so we can solve x with the solve() method.
import numpy as np from scipy.linalg import solve, det A = np.array([[4, 2], [3, 1]]) b = np.array([10, 7]) # Check if determinant is non-zero if det(A) != 0: x = solve(A, b) print("Solution x:", x) else: print("Matrix is singular and cannot be solved.")
Output of the above code is as follows
Solution x: [2. 1.]
Example 5: Solving for Matrix solution (x)
When B is a matrix, scipy.linalg.solve() solves the system so that X is a matrix with the same shape as B.
In this example, A is a square matrix, while B is a multi-column matrix. AX=B is satisfied by computing the solution X.
import numpy as np from scipy.linalg import solve A = np.array([[3, 1], [1, 2]]) B = np.array([[5, 6], [7, 8]]) X = solve(A, B) print("\nSolution Matrix X:\n", X) # Verify the solution by checking if A @ X = B verification = np.allclose(np.dot(A, X), B) print("\nVerification (A @ X == B):", verification)
Output of the above code is as follows
Solution Matrix X: [[0.6 0.8] [3.2 3.6]] Verification (A @ X == B): True