import numpy as np
defarray_test():print"The version is:", np.version.version,"
"
a = np.array([1,2,3])
print"a is:",a
print"type(a) is:",type(a),"
"
b = np.array([[1,2],[3,4]])
print"b is:"print b
print"type(b) is:",type(b),"
"
c = np.array([1,2,3],dtype = float)
print"c is:",c
array_test()
代码运行结果:
The version is: 1.8.0
a is: [123]
type(a) is: <type'numpy.ndarray'>
b is:
[[1 2]
[3 4]]type(b) is: <type'numpy.ndarray'>
c is: [ 1.2.3.]
我的numpy版本是1.8.0。a是一个一维数组,b是一个二维数组,而c,则用dtype参数指定了数据类型为float。
再尝试用其他的方式生成数组对象
defspecial_matrix():
a = np.zeros((2,2))
print"type a is:",type(a)
print a,"
"
b = np.ones((2,2))
print"type b is:",type(b)
print b,"
"
c = np.eye(2,dtype=int)
print"type c is:",type(c)
print c,"
"
special_matrix()
运行结果如下:
type a is: <type'numpy.ndarray'>
[[ 0. 0.]
[ 0. 0.]]type b is: <type'numpy.ndarray'>
[[ 1. 1.]
[ 1. 1.]]type c is: <type'numpy.ndarray'>
[[1 0]
[0 1]]
如果我没有记错的话,matlab里也有这几个方法构造特殊矩阵。顾名思义,zeros(m,n)构造的是全0矩阵,ones(m,n)构造的是全1矩阵,而eys(n)构造的是单位阵。。。
4.矩阵求行列式,求逆,求特征值与特征向量
代码如下
import numpy as np
defget_some_trait():
mat = np.array([[1,2],[3,4]])
det = np.linalg.det(mat)
print"the det of mat is:",det,"
"
inv_mat = np.linalg.inv(mat)
print"the inv_mat is:"print inv_mat,"
"
eig1,eig2 = np.linalg.eig(mat)
print"the eig of mat is:",eig1,"
"print"the feature vector of mat is:"print eig2
get_some_trait()
运行结果如下
the det of mat is: -2.0
the inv_mat is:
[[-2. 1. ]
[ 1.5 -0.5]]
the eig of mat is: [-0.372281325.37228132]
the feature vector of mat is:
[[-0.82456484 -0.41597356]
[ 0.56576746 -0.90937671]]
需要注意的是,eig方法返回的是一个元祖,包含有特征值与特征向量。所以童鞋们在使用的时候稍微注意即可。