Here I'd like to share how to deal with matrix calculation with Python (SymPy). For an introduction to how to use SymPy, see
- Matri manipulation
Matri manipulation
Input matrices
To input matrices in Python (SymPy), put the following
import sympy sympy.init_printing() sympy.var('m11, m12, n11, n21') sympy.var('a11, a12, a21, a22, b11, b12, b21, b22') M = sympy.Matrix([ [m11,m12] ]) N = sympy.Matrix([ [n11], [n21] ]) A = sympy.Matrix([ [a11,a12], [a21,a22] ]) B = sympy.Matrix([ [b11,b12], [b21,b22] ])
Here is a matrix of type-, is of , and are of :
Refer matrix elements
A[0,1] # (k ,l) component of matrix A is given by A[ k-1 , l-1 ]
B[1,1]
and so forth.
Operations of matrices (Product, Sum, Scalar multiplication, Power)
By definition of matrix product, for the case of our settings, matrix products
, , , , and etcetera are allowed:
A*B
M*A
B*N
M*B*N
Power of matrices is given by
A**2
A linear combination of the matrices of the same type is obtained by
sympy.var('a, b')
a*A+b*B
Find inverse matrix
A.inv()
or
A**(-1)
Solve simultaneous linear equations
As an application of inverse matrix, let us consider simultaneous linear equations
This is represented in terms of matrices as
Its solution is given by an inverse matrix of
(here we assume the existence of for simplicity) by applying which, one finds
For example, simultaneous equations for three variables , and
is solved by finding the inverse of the matrix
import sympy sympy.init_printing() sympy.var('a, b, c, d, e, f, g, h, i') A3 = sympy.Matrix([ [a, b, c], [d, e, f], [g, h, i] ]) sympy.cancel(A3**(-1))
then the inverse is found to be
where
Finally, take its product with the vector
one finds the solution
To make a comparison with the result using "solve", put
eq1=sympy.Eq(a*x+b*y+c*z, j) eq2=sympy.Eq(d*x+e*y+f*z, k) eq3=sympy.Eq(g*x+h*y+i*z, l) sympy.solve ([eq1, eq2, eq3], [x, y, z])
then
and thus they coincide.
Determinant
Determinant of matrix is calculated by
A.det()
, the minor of is
A.adjugate()
indeed from
A.inv() == 1/(A.det())*A.adjugate()
thus
Identity matrix
Identity matrix is
sympy.eye(2)
The argument specifies the matrix size.
For example,
sympy.simplify(A.inv()*A) == sympy.eye(2)
Trace
A.trace()
Transposed matrix
The transposed matrix of defined by
is obtained by
A.transpose()
Adjoint matrix
The adjoint matrix
is done by
A.adjoint()
Diagonalize matrices
Find eigenvalues
A.eigenvals()
Find eigenvectors
A.eigenvects()