第一篇在這裏:Numpy庫進階教程(一)求解線性方程組
求解特徵值和特徵向量
關於特徵值和特徵向量的介紹,可以點擊這裏
首先創建一個矩陣
In [1]: A=mat("3 -2;1 0")
In [2]: A
Out[2]:
matrix([[ 3, -2],
[ 1, 0]])
在numpy.linalg模塊中,eigvals函數可以計算矩陣的特徵值,而eig函數可以返回一個包含特徵值和對應特徵向量的元組。
使用eigvals函數求解特徵值
In [3]: linalg.eigvals(A)
Out[3]: array([ 2., 1.])
使用eig函數求解特徵值和特徵向量。該函數將返回一個元祖,按列排放着特徵值和對應的特徵向量,其中第一列爲特徵值,第二列爲特徵向量。
In [5]: B=eig(A)
In [6]: B
Out[6]:
(array([ 2., 1.]), matrix([[ 0.89442719, 0.70710678],
[ 0.4472136 , 0.70710678]]))
使用dot函數使矩陣相乘驗證求得的解是否正確
eigenvalues, eigenvectors = np.linalg.eig(A)
print "First tuple of eig", eigenvalues
print "Second tuple of eig\n", eigenvectors
for i in range(len(eigenvalues)):
print "Left", np.dot(A, eigenvectors[:,i])
print "Right", eigenvalues[i] * eigenvectors[:,i]
print
輸出爲
Left [[ 1.78885438]
[ 0.89442719]]
Right [[ 1.78885438]
[ 0.89442719]]
Left [[ 0.70710678]
[ 0.70710678]]
Right [[ 0.70710678]
[ 0.70710678]]
計算矩陣行列式
In [51]: A = np.mat("3 4;5 6")
In [52]: print "A\n", A
A
[[3 4]
[5 6]]
使用det函數計算行列式
In [53]: print "Determinant", np.linalg.det(A)
Determinant -2.0