16

I am looking to solve a problem of the type: Aw = xBw where x is a scalar (eigenvalue), w is an eigenvector, and A and B are symmetric, square numpy matrices of equal dimension. I should be able to find d x/w pairs if A and B are d x d. How would I solve this in numpy? I was looking in the Scipy docs and not finding anything like what I wanted.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Andrew Latham
  • 5,982
  • 14
  • 47
  • 87

2 Answers2

19

For real symmetric or complex Hermitian dense matrices, you can use scipy.linalg.eigh() to solve a generalized eigenvalue problem. To avoid extracting all the eigenvalues you can specify only the desired ones by using subset_by_index:

from scipy.linalg import eigh

eigvals, eigvecs = eigh(A, B, eigvals_only=False, subset_by_index=[0, 1, 2])

One could use eigvals_only=True to obtain only the eigenvalues.

Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
  • Thanks for clearing this up! That example in the docs for this function was pretty unclear at first glance. – Andrew Latham Jul 16 '14 at 02:54
  • This is reassuring for my purposes, @Saullo, but I'm having problems. By my reckoning, eigh is a specialisation of eig. However, if I use eigh and eig with the same inputs I get *completely* different answers. Is there an additional distinction? – Mike Sadler Jun 30 '20 at 16:25
  • @MikeSadler, are you using symmetric matrices as input? – Saullo G. P. Castro Jul 01 '20 at 23:09
  • 2
    @SaulloG.P.Castro, I am - I was checking them in my test case that they were both symmetric and positive definite. I've side-stepped the problem now, but could it be that eig and eigh don necessarily return the results in the same order? – Mike Sadler Jul 03 '20 at 10:27
  • 3
    @MikeSadler Indeed. According to the documentation, `numpy.linalg.eigh` returns "the eigenvalues in ascending order, each repeated according to its multiplicity." There is no predefined eigenvalue order with `numpy.linalg.eig` – EA304GT Dec 29 '21 at 23:06
13

Have you seen scipy.linalg.eig? From the documentation:

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

This method have optional parameter b:

scipy.linalg.eig(a, b=None, ...
b : (M, M) array_like, optional
Right-hand side matrix in a generalized eigenvalue problem. 
          Default is None, identity matrix is assumed.
Alexey Grigorev
  • 2,415
  • 28
  • 47
RomanHotsiy
  • 4,978
  • 1
  • 25
  • 36
  • The problem in OP is `Aw = xBw`. – emesday Jul 15 '14 at 07:54
  • 5
    so, what's the problem? `scipy.linalg.eig(a, b=None,...`: parameter b: _Right-hand side matrix in a generalized eigenvalue problem. Default is None, identity matrix is assumed._ – RomanHotsiy Jul 15 '14 at 07:56