用 numpy 和 scipy 求矩阵特征值和特征向量,并用matplotlib 显示

本文展示了如何使用Python的numpy和scipy.linalg库计算矩阵A的特征值和特征向量,并通过matplotlib进行可视化。实验内容包括设置坐标轴、绘制特征向量以及在特征方向上的一维线性变换。
摘要由CSDN通过智能技术生成

 改编自菊厂的AI数学基础实验

import numpy as np
from scipy.linalg import eig
import matplotlib.pyplot as plt


A = [
    [1,2],
    [2,1]
]
evals,evacs = eig(A)
print(evals, "\n", evacs)  # [ 3.+0.j -1.+0.j]   [[ 0.70710678 -0.70710678] [ 0.70710678  0.70710678]]
evacs = evacs[:, 0],evacs[:, 1]  # 转换成了tuple 类型的 array
print(evacs, type(evacs))  # (array([0.70710678, 0.70710678]), array([-0.70710678,  0.70710678])) <class 'tuple'>
fig, ax = plt.subplots()  # 返回fig 整个图像 ax 坐标轴和所画的图 对象
for spine in ['left', 'bottom']:  # 让坐标轴经过原点
    ax.spines[spine].set_position('zero')
ax.grid(alpha=0.4)  # 画出网格
xmin, xmax = -3, 3
ymin, ymax = -3, 3
ax.set(xlim=(xmin, xmax), ylim=(ymin, ymax))  # 设置坐标轴范围
for v in evacs:  # 画出特征向量
    ax.annotate("", xy=v, xytext=(0, 0), arrowprops=dict(facecolor='blue', shrink=0,alpha=0.6, width=0.5))

x = np.linspace(xmin,xmax,2)  # 画出特征空间
for v in evacs:
    print(v, type(v))
    a = v[1]/v[0]  # 延特征向量方向的单位向量
    print(a)
    ax.plot(x, a*x,'r-', linewidth=0.4)

plt.show()

 

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值