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 A* A -1 = I.

The inv function in the numpy.linalg package can do this for us. Let's invert an example matrix. To invert matrices, perform the following steps:

  1. We will create the example matrix with the mat function that we used in the previous chapters.
    A = np.mat("0 1 2;1 0 3;4 -3 8")
    print "A
    ", A

    The A matrix is printed as follows:

    A
    [[ 0  1  2]
     [ 1  0  3]
     [ 4 -3  8]]
    
  2. Now, we can see the inv function in action, using which we will invert the matrix.
    inverse = np.linalg.inv(A)
    print "inverse of A
    ", inverse

    The inverse matrix is shown as follows:

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

    Tip

    If the matrix is singular or not square, a LinAlgError exception is raised. If you want, you can check the result manually. This is left as an exercise for the reader.

  3. Let's check what we get when we multiply the original matrix with the result of the inv function:
    print "Check
    ", A * inverse

    The result is the identity matrix, as expected.

    Check
    [[ 1.  0.  0.]
     [ 0.  1.  0.]
     [ 0.  0.  1.]]
    

What just happened?

We calculated the inverse of a matrix with the inv function of the numpy.linalg package. We checked, with matrix multiplication, whether this is indeed the inverse matrix (see inversion.py).

import numpy as np

A = np.mat("0 1 2;1 0 3;4 -3 8")
print "A
", A

inverse = np.linalg.inv(A)
print "inverse of A
", inverse

print "Check
", A * inverse

Pop quiz – creating a matrix

Q1. Which function can create matrices?

  1. array
  2. create_matrix
  3. mat
  4. vector

Have a go hero – inverting your own matrix

Create your own matrix and invert it. The inverse is only defined for square matrices. The matrix must be square and invertible; otherwise, a LinAlgError exception is raised.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset