%=====================  EVMETHODS.m ======================
%     Compare two methods for computing the eigenvalues of a matrix
%      (1): Use MATLAB's "eig" function
%      (2): Compute roots of the characteristic polynomial
%      USAGE: At the MATLAB prompt, define 
%            m = dimension of the test matrix
for m=10:2:30,

% Define the test matrix
B = diag(ones(m-1,1),1);
A = 2*eye(m) - B - B';

%   Compute exact eigenvalues and sort in increasing order
z = pi/(m+1): pi/(m+1): pi*m/(m+1) ;
exact = sort(2+2*cos(z)); 
exact = exact(:);

% Compute eigenvalues using Matlab's  eig function,
%  and sort in increasing order.
xeig = sort(eig(A)); 
xeig = xeig(:);

% Compute roots of the characteristic polynomial.
p = poly(A);
xpoly = sort(roots(p)); 
xpoly = xpoly(:);

% Display results
disp('Eigenvalues from eig, error, e-values from poly, error')
[xeig, abs(xeig-exact), xpoly, abs(xpoly-exact)]

% Plot the computed eigenvalues in the complex plane.
plot(real(xeig), imag(xeig), 'o', real(xpoly), imag(xpoly), 'x')
title(['m =  ', num2str(m)])
axis('equal')

pause
end

