%% Generalized Eigenvalues Where One Matrix is Singular
% Create a 2-by-2 identity matrix, A, and a singular matrix, B.

A = eye(2);
B = [3 6; 4 8];

% If you attempt to calculate the generalized eigenvalues of the matrix B^{-1}A with the command [V,D] = eig(B\A), then MATLAB® returns an error because B\A produces Inf values.
%
% Instead, calculate the generalized eigenvalues and right eigenvectors by passing both matrices to the eig function.

[V,D] = eig(A,B)

% It is better to pass both matrices separately, and let eig choose the best algorithm to solve the problem. In this case, eig(A,B) returns a set of eigenvectors and at least one real eigenvalue, even though B is not invertible.
%
% Verify A v = \lambda B v for the first eigenvalue and the first eigenvector.

eigval = D(1,1);
eigvec = V(:,1);
A*eigvec - eigval*B*eigvec

% Ideally, the eigenvalue decomposition satisfies the relationship. Since the decomposition is performed using floating-point computations, then A*eigvec can, at best, approach eigval*B*eigvec, as it does in this case.
% Copyright 2012 The MathWorks, Inc.