包含特征值的函数上的网格

meshgrid over a function containing eigenvalues

我需要评估包含变量的矩阵的特征值(请参阅下面的简化代码)。函数"test"稍后进入其他函数,最后我想在网格上评估函数。

到目前为止,我正在使用 np.vectorize 和嵌套 for 循环(非常慢)并希望通过在函数上使用 numpy.meshgrid 来提高评估速度。但是,我唯一收到的是错误消息

Traceback (most recent call last):
  File "test.py", line 8, in <module>
    print(test(xx,yy))
  File "test.py", line 4, in test
    return np.linalg.eig(np.array([[1,x],[2,y]]))
ValueError: setting an array element with a sequence.

我通读了帖子

Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence?

但不明白如何将那里提供的解决方案应用到我的问题中。

import numpy as np

def test(x,y):
    return np.linalg.eig(np.array([[1,x],[2,y]]))

xx,yy =np.meshgrid(np.linspace(0,1,5),np.linspace(0,1,5),sparse=True)

print(test(xx,yy))

你的问题是这一行:

np.array([[1,x],[2,y]])

xx 已经是形状为 (1,5) 的矩阵,而 yy 的形状为 (5,1),因此上述行不起作用。

不太清楚您想如何连接这些矩阵,但假设您以某种方式连接起来,np.linalg.eig 需要一个方形数组。

如果我敢猜测,您想创建具有密集网格的 xx,yy,并在网格上计算某个函数 f(x,y) - 这将为您提供一个方形数组,您可以然后使用 np.linalg.eig

例如:

import numpy as np

def test(z):
   w,v = np.linalg.eig(z)
   return w #These are the eigenvalues

xx,yy = np.meshgrid(np.linspace(0, 1, 5), np.linspace(0, 1, 5), sparse=False)
z = np.sin(xx**2 + y**2)
print(test(z))