Time for action – inverting matrices

The inverse of a matrix A in linear algebra is the matrix A-1, which, when multiplied with the original matrix, is equal to the identity matrix I. This can be written as follows:

A A-1 = I

The inv() function in the numpy.linalg package can invert an example matrix with the following steps:

  1. Create the example matrix with the mat() function we used in the previous chapters:
    A = np.mat("0 1 2;1 0 3;4 -3 8")
    print("A\n", A)

    The A matrix appears as follows:

    A
    [[ 0  1  2]
     [ 1  0  3]
     [ 4 -3  8]]
    
  2. Invert the matrix with the inv() function:
    inverse = np.linalg.inv(A)
    print("inverse of A\n", inverse)

    The inverse matrix appears as follows:

    inverse of A
    [[-4.5  7.  -1.5]
     [-2.   4.  -1. ]
     [ 1.5 -2.   0.5]]
    

    Tip

    If the matrix is singular, ...

Get NumPy : Beginner's Guide - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.