Home > Backend Development > Python Tutorial > How to invert a matrix or nArray in Python?

How to invert a matrix or nArray in Python?

WBOY
Release: 2023-09-09 11:29:02
forward
1541 people have browsed it

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"
Copy after login

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)
Copy after login

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)
Copy after login

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]]
Copy after login

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)
    
    Copy after login

    Output

    The input numpy 2D matrix:
    [[5 2]
    [7 3]]
    The Inverse of 2-Dimensional(2x2) numpy matrix:
    [[ 3. -2.]
    [-7. 5.]]
    
    Copy after login

    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)
      
      Copy after login

      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]]
      
      Copy after login

      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!

      source:tutorialspoint.com
      Statement of this Website
      The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
      Popular Tutorials
      More>
      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template