Pymatrix is a lightweight matrix library which supports basic linear algebra operations. The elements in matrix should be numeric type to support basic algebra operations – int, float, rational, complex.
Instantiating Matrix
- Using Matrix constructor
Matrix can be initialised using constructor of Matrix class in pymatrix library.
Syntax: Matrix(rows, cols, fill=val(optional))
Parameters:
rows – specify number of rows
cols – specify number of columns
fill – initialise all the elements with this value. It is an optional argument, the default fill is 0.
- Example:
Python3
import pymatrix m = pymatrix.Matrix( 2 , 3 , fill = '2' ) print (m) |
- Output:
2 2 2 2 2 2
- Using list of lists
We can convert a list of lists into a matrix using the from_list() method where each list is treated as a row. Example-
Python3
import pymatrix list = [[ 1 , 2 , 3 ], [ 6 , 4 , 7 ], [ 3 , 9 , 1 ]] m = pymatrix.Matrix.from_list( list ) print (m) |
- Output:
1 2 3 6 4 7 3 9 1
- Using string
We can convert a string into matrix object using from_string() method. The string is in triple quotes and each line is treated as a row. Example
Python3
import pymatrix string = '''1 2 3 6 4 7 3 9 1''' m = pymatrix.Matrix.from_string(string) print (m) |
- Output:
1 2 3 6 4 7 3 9 1
Matrix methods
Following are some of the methods provided in pymatrix library :
- identity(n) – Creating an identity matrix of given size. This returns an object of Matrix class.
- is_square() – Checks whether given matrix is a square matrix or not. This returns a boolean value.
- is_invertible() – Checks whether given matrix is invertible or not. This returns a boolean value.
- inv() – Returns the inverse matrix if it exists, otherwise raises MatrixError exception.
- det() – Returns the determinant matrix if square matrix, otherwise raises MatrixError(‘non-square matrix does not have determinant’) exception.
- rank() – Returns the rank of matrix, rank is of integer type.
- trans() – Returns the transpose of the matrix.
- adjoint() – Returns the adjoint matrix.
Example:
Python3
# Python program for Matrix methods from pymatrix import Matrix # identity matrix of size 2 identity_matrix = Matrix.identity( 2 ) print ( '\nIdentity matrix :' ) print (identity_matrix) m = Matrix.from_list([[ 1 , 2 , 1 ],[ 2 , 1 , 1 ],[ 1 , 1 , 1 ]]) print ( '\nIs a square matrix :' ) print (m.is_square()) print ( '\nIs an invertible matrix :' ) print (m.is_invertible()) print ( '\nInverse :' ) print (m.inv()) print ( '\nDeterminant :' ) print (m.det()) print ( '\nRank :' ) print (m.rank()) print ( '\nTranspose :' ) print (m.trans()) print ( '\nAdjoint :' ) print (m.adjoint()) |
Output:
Identity matrix : 1 0 0 1 Is a square matrix : True Is an invertible matrix : True Inverse : 0.0 1.0 -1.0 1.0 0.0 -1.0 -1.0 -1.0 3.0 Determinant : -1.0 Rank : 3 Transpose : 1 2 1 2 1 1 1 1 1 Adjoint : 0.0 -1.0 1.0 -1.0 0.0 1.0 1.0 1.0 -3.0