search
HomeBackend DevelopmentPython TutorialHow to invert a matrix or nArray in Python?

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!

      Statement
      This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
      Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

      Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

      Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

      Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

      The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

      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.

      Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

      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.

      How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

      You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

      How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

      How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

      How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

      How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

      What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?Apr 02, 2025 am 07:12 AM

      Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

      See all articles

      Hot AI Tools

      Undresser.AI Undress

      Undresser.AI Undress

      AI-powered app for creating realistic nude photos

      AI Clothes Remover

      AI Clothes Remover

      Online AI tool for removing clothes from photos.

      Undress AI Tool

      Undress AI Tool

      Undress images for free

      Clothoff.io

      Clothoff.io

      AI clothes remover

      AI Hentai Generator

      AI Hentai Generator

      Generate AI Hentai for free.

      Hot Article

      R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
      3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
      R.E.P.O. Best Graphic Settings
      3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
      R.E.P.O. How to Fix Audio if You Can't Hear Anyone
      3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
      WWE 2K25: How To Unlock Everything In MyRise
      4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

      Hot Tools

      Safe Exam Browser

      Safe Exam Browser

      Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

      MantisBT

      MantisBT

      Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

      SAP NetWeaver Server Adapter for Eclipse

      SAP NetWeaver Server Adapter for Eclipse

      Integrate Eclipse with SAP NetWeaver application server.

      SublimeText3 English version

      SublimeText3 English version

      Recommended: Win version, supports code prompts!

      SublimeText3 Mac version

      SublimeText3 Mac version

      God-level code editing software (SublimeText3)