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
      How do you append elements to a Python list?How do you append elements to a Python list?May 04, 2025 am 12:17 AM

      ToappendelementstoaPythonlist,usetheappend()methodforsingleelements,extend()formultipleelements,andinsert()forspecificpositions.1)Useappend()foraddingoneelementattheend.2)Useextend()toaddmultipleelementsefficiently.3)Useinsert()toaddanelementataspeci

      How do you create a Python list? Give an example.How do you create a Python list? Give an example.May 04, 2025 am 12:16 AM

      TocreateaPythonlist,usesquarebrackets[]andseparateitemswithcommas.1)Listsaredynamicandcanholdmixeddatatypes.2)Useappend(),remove(),andslicingformanipulation.3)Listcomprehensionsareefficientforcreatinglists.4)Becautiouswithlistreferences;usecopy()orsl

      Discuss real-world use cases where efficient storage and processing of numerical data are critical.Discuss real-world use cases where efficient storage and processing of numerical data are critical.May 04, 2025 am 12:11 AM

      In the fields of finance, scientific research, medical care and AI, it is crucial to efficiently store and process numerical data. 1) In finance, using memory mapped files and NumPy libraries can significantly improve data processing speed. 2) In the field of scientific research, HDF5 files are optimized for data storage and retrieval. 3) In medical care, database optimization technologies such as indexing and partitioning improve data query performance. 4) In AI, data sharding and distributed training accelerate model training. System performance and scalability can be significantly improved by choosing the right tools and technologies and weighing trade-offs between storage and processing speeds.

      How do you create a Python array? Give an example.How do you create a Python array? Give an example.May 04, 2025 am 12:10 AM

      Pythonarraysarecreatedusingthearraymodule,notbuilt-inlikelists.1)Importthearraymodule.2)Specifythetypecode,e.g.,'i'forintegers.3)Initializewithvalues.Arraysofferbettermemoryefficiencyforhomogeneousdatabutlessflexibilitythanlists.

      What are some alternatives to using a shebang line to specify the Python interpreter?What are some alternatives to using a shebang line to specify the Python interpreter?May 04, 2025 am 12:07 AM

      In addition to the shebang line, there are many ways to specify a Python interpreter: 1. Use python commands directly from the command line; 2. Use batch files or shell scripts; 3. Use build tools such as Make or CMake; 4. Use task runners such as Invoke. Each method has its advantages and disadvantages, and it is important to choose the method that suits the needs of the project.

      How does the choice between lists and arrays impact the overall performance of a Python application dealing with large datasets?How does the choice between lists and arrays impact the overall performance of a Python application dealing with large datasets?May 03, 2025 am 12:11 AM

      ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

      Explain how memory is allocated for lists versus arrays in Python.Explain how memory is allocated for lists versus arrays in Python.May 03, 2025 am 12:10 AM

      InPython,listsusedynamicmemoryallocationwithover-allocation,whileNumPyarraysallocatefixedmemory.1)Listsallocatemorememorythanneededinitially,resizingwhennecessary.2)NumPyarraysallocateexactmemoryforelements,offeringpredictableusagebutlessflexibility.

      How do you specify the data type of elements in a Python array?How do you specify the data type of elements in a Python array?May 03, 2025 am 12:06 AM

      InPython, YouCansSpectHedatatYPeyFeLeMeReModelerErnSpAnT.1) UsenPyNeRnRump.1) UsenPyNeRp.DLOATP.PLOATM64, Formor PrecisconTrolatatypes.

      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

      Video Face Swap

      Video Face Swap

      Swap faces in any video effortlessly with our completely free AI face swap tool!

      Hot Tools

      SAP NetWeaver Server Adapter for Eclipse

      SAP NetWeaver Server Adapter for Eclipse

      Integrate Eclipse with SAP NetWeaver application server.

      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.

      SublimeText3 Chinese version

      SublimeText3 Chinese version

      Chinese version, very easy to use

      Dreamweaver CS6

      Dreamweaver CS6

      Visual web development tools

      Atom editor mac version download

      Atom editor mac version download

      The most popular open source editor