- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Solve a linear matrix equation or system of linear scalar equations in Python
To solve a linear matrix equation, use the numpy.linalg.solve() method in Python. The method computes the “exact” solution, x, of the well-determined, i.e., full rank, linear matrix equation ax = b. Returns a solution to the system a x = b. Returned shape is identical to b. The 1st parameter a is the Coefficient matrix. The 2nd parameter b is the Ordinate or “dependent variable” values.
Steps
At first, import the required libraries -
import numpy as np
Creating two 2D numpy arrays using the array() method. Consider the system of equations x0 + 2 * x1 = 1 and 3 * x0 + 5 * x1 = 2 −
arr1 = np.array([[1, 2], [3, 5]]) arr2 = np.array([1, 2])
Display the arrays −
print("Array1...\n",arr1) print("\nArray2...\n",arr2)
Check the Dimensions of both the arrays −
print("\nDimensions of Array1...\n",arr1.ndim) print("\nDimensions of Array2...\n",arr2.ndim)
Check the Shape of both the arrays −
Print(“\nShape of Array1…\n”,arr1.shape) print("\nShape of Array2...\n",arr2.shape)
To solve a linear matrix equation, use the numpy.linalg.solve() method −
print("\nResult...\n",np.linalg.solve(arr1, arr2))
Example
import numpy as np # Creating two 2D numpy arrays using the array() method # Consider the system of equations x0 + 2 * x1 = 1 and 3 * x0 + 5 * x1 = 2 arr1 = np.array([[1, 2], [3, 5]]) arr2 = np.array([1, 2]) # Display the arrays print("Array1...\n",arr1) print("\nArray2...\n",arr2) # Check the Dimensions of both the arrays print("\nDimensions of Array1...\n",arr1.ndim) print("\nDimensions of Array2...\n",arr2.ndim) # Check the Shape of both the arrays print("\nShape of Array1...\n",arr1.shape) print("\nShape of Array2...\n",arr2.shape) # To solve a linear matrix equation, use the numpy.linalg.solve() method in Python. print("\nResult...\n",np.linalg.solve(arr1, arr2))
Output
Array1... [[1 2] [3 5]] Array2... [1 2] Dimensions of Array1... 2 Dimensions of Array2... 1 Shape of Array1... (2, 2) Shape of Array2... (2,) Result... [-1. 1.]
Advertisements