w3resource

Compute the inverse of a 6x6 random array using NumPy


The inverse of a matrix A is another matrix A-1 such that the product of A and A-1 is the identity matrix. Not all matrices have inverses; only square matrices that are non-singular (having a non-zero determinant) are invertible. The inverse matrix is used in various applications, including solving linear systems and transforming coordinates.

Write a NumPy program to create a 6x6 array with random values and compute the inverse of the matrix.

The task involves generating a 6x6 array filled with random values using NumPy and computing its inverse. The inverse of a matrix is a crucial concept in linear algebra, useful for solving systems of linear equations, performing matrix division, and analyzing linear transformations.

Sample Solution:

Python Code:

# Importing the necessary NumPy library
import numpy as np

# Create a 6x6 array with random values
array = np.random.rand(6, 6)

# Compute the inverse of the matrix
inverse_array = np.linalg.inv(array)

# Printing the array and its inverse
print("Array:\n", array)
print("Inverse of the array:\n", inverse_array)

Output:

Array:
 [[0.59307022 0.73882052 0.60279763 0.97069842 0.99889343 0.28413052]
 [0.50517809 0.46955646 0.11493593 0.04062937 0.71356393 0.03259477]
 [0.2493927  0.69251981 0.45217131 0.11407127 0.14061807 0.86220541]
 [0.20908968 0.83711993 0.50220878 0.63485647 0.43299173 0.82644402]
 [0.30712116 0.42106211 0.57733752 0.25934468 0.96127669 0.18059266]
 [0.81421309 0.09425506 0.39712125 0.23533348 0.17494402 0.68669111]]
Inverse of the array:
 [[ 1.32974609  0.46273517  1.33112669 -2.04174268 -1.0914637   0.50078926]
 [ 1.83771032  0.43426957  2.98393986 -2.28519526 -1.38182995 -1.41393894]
 [ 2.81423588 -2.57812288  4.36785346 -4.91912221  0.710505   -0.79292817]
 [ 0.51798739 -0.45793243 -1.38281501  1.21097303 -0.585216    0.24014444]
 [-2.49655718  1.19581519 -3.38562043  3.47719163  1.56089406  0.63184274]
 [-2.99792008  0.73496855 -3.17744455  4.27848327  0.87582857  1.27183708]]

Explanation:

  • Import NumPy library: This step imports the NumPy library, essential for numerical operations.
  • Create a 6x6 array: We use np.random.rand(6, 6) to generate a 6x6 matrix with random values between 0 and 1.
  • Compute the inverse of the matrix: The np.linalg.inv function calculates the inverse of the given array.
  • Print results: This step prints the original array and its inverse.

Python-Numpy Code Editor: