Time for action – creating matrices

Matrices can be created with the mat function. This function does not make a copy if the input is already a matrix or an ndarray. Calling this function is equivalent to calling matrix(data, copy=False). We will also demonstrate transposing and inverting matrices.

  1. Rows are delimited by a semicolon, values by a space. Call the mat function with the following string to create a matrix:
    A = np.mat('1 2 3; 4 5 6; 7 8 9')
    print "Creation from string", A

    The matrix output should be the following matrix:

    Creation from string [[1 2 3]
     [4 5 6]
     [7 8 9]]
    
  2. Transpose the matrix with the T attribute, as follows:
    print "transpose A", A.T

    The following is the transposed matrix:

    transpose A [[1 4 7]
     [2 5 8]
     [3 6 9]]
    
  3. The matrix can be inverted with the I attribute, as follows:
    print "Inverse A", A.I

    The inverse matrix is printed as follows (be warned that this is a O(n3) operation):

    Inverse A [[ -4.50359963e+15   9.00719925e+15  -4.50359963e+15]
     [  9.00719925e+15  -1.80143985e+16   9.00719925e+15]
     [ -4.50359963e+15   9.00719925e+15  -4.50359963e+15]]
    
  4. Instead of using a string to create a matrix, let's do it with an array:
    print "Creation from array", np.mat(np.arange(9).reshape(3, 3))

    The newly-created array is printed as follows:

    Creation from array [[0 1 2]
     [3 4 5]
     [6 7 8]]
    

What just happened?

We created matrices with the mat function. We transposed the matrices with the T attribute and inverted them with the I attribute (see matrixcreation.py):

import numpy as np

A = np.mat('1 2 3; 4 5 6; 7 8 9')
print "Creation from string", A
print "transpose A", A.T
print "Inverse A", A.I
print "Check Inverse", A * A.I 

print "Creation from array", np.mat(np.arange(9).reshape(3, 3))
..................Content has been hidden....................

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