How to invert a matrix or nArray in Python?
In this article, we will show you how to calculate the inverse of a matrix or ndArray using the NumPy library in Python.
What is the inverse matrix of a matrix?
The inverse of a matrix is such that if it is multiplied by the original matrix, it results in the identity matrix.
The inverse of a matrix is simply the reciprocal of a matrix, as in regular arithmetic, for a single number used to solve equations to obtain the values of unknown variables. The inverse of a matrix is the matrix that when multiplied by the original matrix produces the identity matrix.
The inverse of a matrix exists only when the matrix is non-singular, that is, the determinant is not 0. We can simply find the inverse of a square matrix using the determinant and adjoint matrix using the following formula
if det(A) != 0 A-1 = adj(A)/det(A) else "Inverse does not exist"
Method 1 - Use numpy.linalg.inv() function on np.array() type
numpy.linalg.inv() function
Python has a very simple way to calculate the inverse of a matrix. To compute the inverse of a matrix, use the numpy.linalg.inv() function from the NumPy module in Python to bypass the matrix.
grammar
numpy.linalg.inv(array)
parameter
array - It is a matrix that must be inverted.
Return value - The numpy.linalg.inv() function returns the inverse matrix of the matrix.
Algorithm (steps)
The following are the algorithms/steps that need to be followed to perform the required task -
Use the import keyword to import the numpy module with an alias (np).
Use the numpy.array() function (returns an ndarray. ndarray is an array object that meets the given requirements) to create a numpy array array(3rows, 3columns) by passing a 3-dimensional array as its parameters.
Use the linalg.inv() function of the numpy module (Compute the inverse of a matrix) to compute the inverse of an input 3x3 matrix by passing the input matrix as an argument and print the inverse matrix.
Example
The following program uses the numpy.linalg.inv() function to return the inverse matrix of the input 3-dimensional (3x3) matrix-
# importing numpy module with an alias name import numpy as np # creating a 3-Dimensional(3x3) numpy matrix inputArray_3d = np.array([[4, 5, 1], [3, 4, 12], [10, 2, 1]]) # printing the input 3D matrix print("The input numpy 3D matrix:") print(inputArray_3d) # calculating the inverse of an input 3D matrix resultInverse= np.linalg.inv(inputArray_3d) # printing the resultant inverse of an input matrix print("The Inverse of 3-Dimensional(3x3) numpy matrix:") print(resultInverse)
Output
When executed, the above program will generate the following output -
The input numpy 3D matrix: [[ 4 5 1] [ 3 4 12] [10 2 1]] The Inverse of 3-Dimensional(3x3) numpy matrix: [[-0.04246285 -0.00636943 0.11889597] [ 0.24840764 -0.01273885 -0.0955414 ] [-0.07218684 0.08917197 0.00212314]]
Method 2 - Using scipy.linalg.inv() function
scipy.linalg.inv()
Using the functions of the scipy module, we can perform various scientific calculations. It also works with numpy arrays.
In Python, scipy.linalg.inv() can also return the inverse matrix of a given square matrix. It works the same as numpy.linalg.inv() function.
Algorithm (steps)
The following are the algorithms/steps that need to be followed to perform the required task -
Use the import keyword to import linalg from the scipy module.
Use the numpy.matrix() function (returns a matrix from a data string or array-like object. The resulting matrix is a specialized two-dimensional array) for creating numpy matrices, By passing it a 2D array (2 rows, 2 columns) as a parameter.
Use the linalg.inv() function of the scipy module (Compute the inverse of a matrix) to compute the inverse of an input 2x2 matrix by passing the input matrix as an argument and print the inverse matrix.
Example
import numpy as np # importing linalg from scipy module from scipy import linalg # creating a 2-Dimensional(2x2) NumPy matrix inputMatrix = np.matrix([[5, 2],[7, 3]]) # printing the input 2D matrix print("The input numpy 2D matrix:") print(inputMatrix) # calculating the inverse of an input 2D matrix resultInverse = linalg.inv(inputMatrix) # printing the resultant inverse of an input matrix print("The Inverse of 2-Dimensional(2x2) numpy matrix:") print(resultInverse)
Output
The input numpy 2D matrix: [[5 2] [7 3]] The Inverse of 2-Dimensional(2x2) numpy matrix: [[ 3. -2.] [-7. 5.]]
Method 3 - Using numpy.linalg.inv() function on np.matrix() type
Algorithm (steps)
The following are the algorithms/steps that need to be followed to perform the required task -
Use the numpy.matrix() function (returns a matrix from a data string or array-like object. The resulting matrix is a specialized 4D array) for creating a numpy matrix, by Pass it a 4-dimensional array (4 rows, 4 columns) as a parameter.
Example
import numpy as np # creating a NumPy matrix (4x4 matrix) using matrix() method inputMatrix = np.matrix('[11, 1, 8, 2; 11, 3, 9 ,1; 1, 2, 3, 4; 9, 8, 7, 6]') # printing the input 4D matrix print("The input NumPy matrix:") print(inputMatrix) # calculating the inverse of an input matrix resultInverse= np.linalg.inv(inputMatrix) # printing the resultant inverse of an input matrix print("The Inverse of 4-Dimensional(4x4) numpy matrix:") print(resultInverse)
Output
The input NumPy matrix: [[11 1 8 2] [11 3 9 1] [ 1 2 3 4] [ 9 8 7 6]] The Inverse of 4-Dimensional(4x4) numpy matrix: [[ 0.25 -0.23214286 -0.24107143 0.11607143] [-0.25 0.16071429 -0.09464286 0.11964286] [-0.25 0.375 0.3125 -0.1875 ] [ 0.25 -0.30357143 0.12321429 0.05178571]]
in conclusion
In this article, we learned how to calculate the inverse of a matrix using three different examples. We learned how to get matrices in Numpy using two different methods: numpy.array() and NumPy.matrix().
The above is the detailed content of How to invert a matrix or nArray in Python?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

As a data professional, you need to process large amounts of data from various sources. This can pose challenges to data management and analysis. Fortunately, two AWS services can help: AWS Glue and Amazon Athena.

The steps to start a Redis server include: Install Redis according to the operating system. Start the Redis service via redis-server (Linux/macOS) or redis-server.exe (Windows). Use the redis-cli ping (Linux/macOS) or redis-cli.exe ping (Windows) command to check the service status. Use a Redis client, such as redis-cli, Python, or Node.js, to access the server.

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

Question: How to view the Redis server version? Use the command line tool redis-cli --version to view the version of the connected server. Use the INFO server command to view the server's internal version and need to parse and return information. In a cluster environment, check the version consistency of each node and can be automatically checked using scripts. Use scripts to automate viewing versions, such as connecting with Python scripts and printing version information.

Navicat's password security relies on the combination of symmetric encryption, password strength and security measures. Specific measures include: using SSL connections (provided that the database server supports and correctly configures the certificate), regularly updating Navicat, using more secure methods (such as SSH tunnels), restricting access rights, and most importantly, never record passwords.
