用matplotlib绘制特征向量及其变换
在mpl中,我们使用plt.quiver函数绘制矢量。
import matplotlib.pyplot as plt
import numpy as np
import numpy.linalg as npl
fig=plt.figure()
ax=plt.axes()
plt.grid()
m=input("input the mat:")#输入一个二维矩阵,如:1 4 5 7即[[1,4],[5,7]]
mat0=np.mat(m).reshape(2,2)
ax.set(xlabel="x",ylabel="y",
title="The eigenvectors of the 2-D matrix:[{x}]".format(x=m))
a=np.linspace(0,2*np.pi,1000)
x0=np.cos(a)
y0=np.sin(a)
x1=mat0[0,0]*x0+mat0[0,1]*y0
y1=mat0[1,0]*x0+mat0[1,1]*y0
ax.plot(x0,y0,label="unit circle")
ax.plot(x1,y1,label="after transfor")
plt.axis("equal")
#该函数返回矩阵mat0和二维向量v0的乘积,即变换后的向量
def fun0(mat0,v0):
v0=np.mat(v0).reshape(2,1)
return mat0*v0
#选取四个向量,以大体展示矩阵对单位圆的变换。
v0=[-1,0]
v1=[1,0]
v2=[0,1]
v3=[0,-1]
ax.quiver([-1,1,0,0],#横坐标
[0,0,1,-1],#纵坐标
[fun0(mat0,v0)[0,0]+1,
fun0(mat0,v1)[0,0]-1,
fun0(mat0,v2)[0,0],
fun0(mat0,v3)[0,0]],
[fun0(mat0,v0)[1,0],
fun0(mat0,v1)[1,0],
fun0(mat0,v2)[1,0]-1,
fun0(mat0,v3)[1,0]+1],
angles='xy', scale_units='xy', scale=1,width=0.002,)
eigvalue,eigvectors=npl.eig(mat0)#特征值,特征向量求解
va0=eigvalue[0]#第一个特征值
va1=eigvalue[1]#第二个特征值
vr0=eigvectors[:,0]#第一个特征向量
vr1=eigvectors[:,1]#第二个特征向量
ax.quiver(0,0,vr0[0],vr0[1],#画出第一个特征向量
angles='xy', scale_units='xy', scale=1,width=0.002,
label="vr0;va0={}".format(va0),color="r")
ax.quiver(0,0,(mat0*vr0)[0,0],(mat0*vr0)[1,0],#画出变换后的特征向量
angles='xy', scale_units='xy', scale=1,width=0.002,color="r")
ax.quiver(0,0,vr1[0],vr1[1],#画出第二个特征向量
angles='xy', scale_units='xy', scale=1,width=0.002,color="b",
label="vr1;va1={}".format(va1))
ax.quiver(0,0,(mat0*vr1)[0,0],(mat0*vr1)[1,0],#画出变换后的特征向量
angles='xy', scale_units='xy', scale=1,width=0.002,color="b")
plt.legend()
print("特征值为:",eigvalue)
print("特征向量为:\n",vr0)
print("变换后的特征向量为:\n",va0*vr0)
plt.show()
演示:
input the mat:1 6 5 2
特征值为: [-4. 7.]
特征向量为:
[[-0.76822128]
[ 0.6401844 ]]
变换后的特征向量为:
[[ 3.07288512]
[-2.5607376 ]]

input the mat:4 1 2 7
特征值为: [3.43844719 7.56155281]
特征向量为:
[[-0.87192821]
[ 0.48963374]]
变换后的特征向量为:
[[-2.9980791 ]
[ 1.68357975]]

对欠秩矩阵的求解:
input the mat:4 1 8 2
特征值为: [6. 0.]
特征向量为:
[[0.4472136 ]
[0.89442719]]
变换后的特征向量为:
[[2.68328157]
[5.36656315]]


浙公网安备 33010602011771号