Book Image

NumPy: Beginner's Guide

By : Ivan Idris
Book Image

NumPy: Beginner's Guide

By: Ivan Idris

Overview of this book

Table of Contents (21 chapters)
NumPy Beginner's Guide Third Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
NumPy Functions' References
Index

Time for action – creating matrices


The mat() 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 and 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 (see https://www.khanacademy.org/math/precalculus/precalc-matrices/inverting_matrices/v/inverse-matrix-part-1):

    print("Inverse A", A.I)

    The inverse matrix is printed as follows (be warned that this is a O(n3) operation, meaning that it takes...