%% Eigenvalues That Are Sensitive to Round-off Errors
% Create the test matrix A = gallery(5). The test matrix has eigenvalues that are sensitive to round-off errors.

A = gallery(5)

% In exact arithmetic, the matrix A has five-fold eigenvalues of \lambda = 0 (strictly speaking, A has an eigenvalue 0 of algebraic multiplicity 5 and geometric multiplicity 1). This means that the exact characteristic polynomial of A is \lambda^5 = 0. Verify that A^5 is a zero matrix.

Afifth = A^5

% Compare these results with the numerical computation of eigenvalues using eig. The eig function returns five eigenvalues of A that are small.

e = eig(A)

% This suggests that the numerical computation of the eigenvalues of A is extremely sensitive to round-off errors due to the floating-point precision used in the computation.
% Numerical computations of eigenvalues are very different from their counterparts in exact arithmetic. Instead of finding eigenvalues that are close to the exact eigenvalues of A, the eig function finds eigenvalues of a matrix that is close to A. To illustrate this, plot the exact and numerical eigenvalues of A in the complex plane.

plot(0,0,'bo',real(e),imag(e),'r*')
axis([-0.1 0.1 -0.1 0.1])
axis square

% The figure shows that the numerical eigenvalues lie on the vertices of a regular pentagon in the complex plane, centered at the origin. The radius of the pentagon is about 0.04.
% Next, compute the eigenvalues of 20 matrices that are close to A. Set the random number generator to the default value, and perturb A by random numbers drawn from the standard normal distribution multiplied by eps. Plot the numerical eigenvalues of the 20 perturbed matrices.

E = zeros(20,5);
rng('default')
for i = 1:20
  E(i,:) = eig(A + eps*randn(5).*A);
end
plot(0,0,'bo',real(e),imag(e),'r*',real(E),imag(E),'k.')
axis([-0.1 0.1 -0.1 0.1])
axis square

% The figure shows that the original pentagon, which represents the eigenvalues of A, can flip orientation when A is perturbed. The eigenvalues of the 20 perturbed matrices lie on the vertices of pentagons with radii in the range of 0.01 to 0.07. The computed eigenvalues of the perturbed matrices behave similarly to the computed eigenvalues of the original matrix. The inaccuracy of the computed eigenvalues is caused by the sensitivity of gallery(5).
%
% Copyright 2019 The MathWorks, Inc.