%% Eigenvalue problems
% This script explores how to use Matlab to solve eigenvalue problems. Both
% the naive and 'proper' way are shown.
%% The Eig function
% The simplest way to compute eigenvalues and eigenvectors in Matlab is to
% use the built in "eig" function.
A=rand(10);
tic
EigVal1=eig(A)
toc
%%
% This will produce a column vector of the eigenvalues of A. To also get
% the eigenvectors, return two outputs:
tic
[EigVec2,EigVal2]=eig(A);
toc
%%
% This will return the eigenvectors as the columns of EigVec, and the
% eigenvalues as the entries of the diagonal matrix EigVal.
 
%% Root Solving
% We can also use Matlab to solve an eigenvalue problem in the direct way
% one would do it on paper. We can calculate the characteristic polynomial
% of our matrix and then find the roots. Using the built in functions
% charpoly and roots, this is:
tic
EigVal3=roots(charpoly(A))
toc
 
%% Large matrices
% As you can see in the timings, this method is significantly slower than
% using the built in function. For large enough matrices, it is not
% feasible to solve the problem algebraically.
A=rand(1000);
tic
EigVal4=eig(A)
toc
tic
[EigVec5,EigVal5]=eig(A);
toc
%%
% If the matrix you are considering is very large, you may not want all of
% the eigenvalues, in this case you can use:
tic
EigVal6=eigs(A);
toc
%%
% This returns the largest (in magnitude) six eigenvalues of the matrix.
% The function works the same as the previous one to calculate
% eigenvectors.
tic
[EigVec7,EigVal7]=eigs(A)
toc
%%
% If you specify a number, k, after the matrix, the function will return the
% largest k eigenvalues.
tic
EigVal8=eigs(A,1)
toc


