关于NumPy函数库的基础学习(1)

时间:2021-08-04 21:20:01

1、导入NumPy函数库:from numpy import *

>>> from numpy import *

2、构造一个4×4的随机数组:random.rand(4,4)

>>> random.rand(4,4)
array([[ 0.64892253, 0.36155878, 0.61115192, 0.45250833],
[ 0.70489894, 0.13712867, 0.08937807, 0.15836451],
[ 0.79766943, 0.29951048, 0.15084045, 0.11801158],
[ 0.61060769, 0.54188315, 0.02381909, 0.47742619]]
)

运用mat()函数可以将数组转化为矩阵:randmat = mat(random.rand(4,4))

>>> randMat = mat(random.rand(4,4))
>>> randMat
matrix([[ 0.46870389, 0.29488197, 0.25697642, 0.60788096],
[ 0.85256998, 0.71392001, 0.66044905, 0.08788728],
[ 0.07374033, 0.62702406, 0.9281263 , 0.8972311 ],
[ 0.91063226, 0.60722426, 0.68104652, 0.39539063]]
)

3、矩阵求逆:matrix.I

>>> randMat.I
matrix([[-0.1579925 , -1.26453206, -0.84057206, 2.43142917],
[ 3.8955427 , 6.35083704, 0.25143617, -7.9713078 ],
[-4.22850815, -3.64324385, 0.7875871 , 5.52359263],
[ 1.66472277, -0.56561813, 0.19320244, -0.34292636]]
)

4、矩阵乘法:matrix1 * matrix2

>>> invRandMat = randMat.I
>>> randMat * invRandMat
matrix([[ 1.00000000e+00, -2.77555756e-16, 4.16333634e-17, 2.77555756e-17],
[ -4.16333634e-16, 1.00000000e+00, 1.07552856e-16, -5.41233725e-16],
[ 2.22044605e-16, -2.22044605e-16, 1.00000000e+00, -1.11022302e-16],
[ 1.11022302e-16, 1.11022302e-16, 4.16333634e-17, 1.00000000e+00]]
)

5、构造单位矩阵:eye(num)

>>> eye(4)
array([[ 1., 0., 0., 0.],
[ 0., 1., 0., 0.],
[ 0., 0., 1., 0.],
[ 0., 0., 0., 1.]]
)