Python 中的 eig(a,b) 给出错误 "takes 1 positional argument but 2 were given"

eig(a,b) in Python giving error "takes 1 positional argument but 2 were given"

根据 https://docs.scipy.org/doc/numpy-1.15.0/user/numpy-for-matlab-users.html,MATLAB [V,D]=eig(a,b) 的等效 numpy 表达式是 V,D = np.linalg.eig(a,b)

但是当我尝试这个时,我得到了错误:

TypeError: eig() takes 1 positional argument but 2 were given

我很困惑,文档说 np.linalg.eig 可以接受两个参数?

奇怪的是,当我查看 https://docs.scipy.org/doc/numpy-1.15.1/reference/routines.linalg.html 上的 linalg 文档时,在标题 'Matrix eigenvalues' 下没有提到 linalg.eig 采用两个参数?

如何让 eig 像在 MATLAB 中一样接受两个参数?

这适用于 MATLAB

a = diag(ones(3,1));
b = diag(2*ones(3,1));
[V,D] = eig(a,b)

输出:

V =

    0.7071         0         0
         0    0.7071         0
         0         0    0.7071


D =

    0.5000         0         0
         0    0.5000         0
         0         0    0.5000

这在 Python

中不起作用
import numpy as np

a = np.diag(np.ones(3))
b = np.diag(2*np.ones(3))

V,D = np.linalg.eig(a,b)

错误:

TypeError: eig() takes 1 positional argument but 2 were given

正如您在 numpy.linalg.eig 的文档中看到的那样,它只接受一个数组参数,相应地它不计算广义特征值问题。

幸运的是我们有scipy.linalg.eig:

scipy.linalg.eig(a, b=None, left=False, right=True, overwrite_a=False, overwrite_b=False, check_finite=True, homogeneous_eigvals=False)

    Solve an ordinary or generalized eigenvalue problem of a square matrix.

这是您的示例案例:

import numpy as np 
import scipy.linalg 

a = np.diag(np.ones(3)) 
b = np.diag(2*np.ones(3)) 
eigvals,eigvects = scipy.linalg.eig(a, b) 

现在我们有

>>> eigvals
array([0.5+0.j, 0.5+0.j, 0.5+0.j])

>>> eigvects
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])

特征向量的差异可能是由于特征值归一化的不同选择。我会检查两个非平凡矩阵,看看结果是否相互对应(当然是比较相应的特征值-特征向量对)。