## Notes on Python cookbook 3rd (3.10): matrix and linear algebra operation

Giant ship 2020-11-18 00:30:40
notes python cookbook 3rd rd

# Matrix and linear algebra operations

## problem

You need to perform matrix and linear algebra operations , Like matrix multiplication 、 Look for determinants 、 Solving linear equations and so on .

## solution

NumPy The library has a matrix object that can be used to solve this problem . The matrix is similar to 3.9 Array objects in the section , But follow the rules of linear algebra . Here's an example It shows some basic properties of matrix ：

``````>>> import numpy as np
>>> m = np.matrix([[1,-2,3],[0,4,5],[7,8,-9]])
>>> m
matrix([[ 1, -2, 3],
[ 0, 4, 5],
[ 7, 8, -9]])
>>> # Return transpose
>>> m.T
matrix([[ 1, 0, 7],
[-2, 4, 8],
[ 3, 5, -9]])
>>> # Return inverse
>>> m.I
matrix([[ 0.33043478, -0.02608696, 0.09565217],
[-0.15217391, 0.13043478, 0.02173913],
[ 0.12173913, 0.09565217, -0.0173913 ]])
>>> # Create a vector and multiply
>>> v = np.matrix([,,])
>>> v
matrix([,
,
])
>>> m * v
matrix([[ 8],
,
[ 2]])
>>>
``````

Can be in numpy.linalg Find more operation functions in the subpackage , such as ：

``````>>> import numpy.linalg
>>> # Determinant
>>> numpy.linalg.det(m)
-229.99999999999983
>>> # Eigenvalues
>>> numpy.linalg.eigvals(m)
array([-13.11474312, 2.75956154, 6.35518158])
>>> # Solve for x in mx = v
>>> x = numpy.linalg.solve(m, v)
>>> x
matrix([[ 0.96521739],
[ 0.17391304],
[ 0.46086957]])
>>> m * x
matrix([[ 2.],
[ 3.],
[ 4.]])
>>> v
matrix([,
,
])
>>>
``````

## Discuss

Obviously, linear algebra is a very big subject , It's beyond the scope of this book . however , If you need to manipulate arrays and vectors , NumPy It's a good entry point . You can visit NumPy Official website For more information .