%% Week 7
% Matlab codes for week 7

%% Problem 1

A=[4.2,-0.1,0.2,0.1;0.05,3,-0.1,-0.05;0.5,-0.5,2,0.1;0.1,0.2,0.3,-1]
eig(A)

%% Problem 2

% a)

A=[3,1;1,3]
eig(A) % eigenvalues of A
A(2,1)=A(2,1)+0.1
eig(A) % eigenvalues of the perturbed matrix

% Change of eigenvalues
change_of_eigenvalues=norm([0,0;0.1,0])


%%

% b) 

A=[9,2;1,3]
eig(A) % eigenvalues of A

A(2,1)=A(2,1)+0.1
eig(A) % eigenvalues of the perturbed matrix

[V,S]=eig(A)
inv(V)*A*V % A can be diagonalized with the matrix of the eigenvectors.

% Change of eigenvalues
change_of_eigenvalues=norm([0,0;0.1,0])*cond(V)

%% Problem 3

A = [2,1,0;1,2,1;0,1,2]
eig(A)

%%
% power method

y=rand(size(A,1),1);
for i=1:50
  i
  x=A*y;
  y=x/norm(x)
  nu=y'*A*y
  pause
end

%% Problem 4

A=toeplitz([20:-1:1]);

tic
for i=1:100
    [Q,R]=qr(A);
    A=R*Q
    pause
end
toc

ev=diag(A)
ev_error=sum(abs(A-diag(diag(A))))'

%% Problem 5

A=[0,1;1,0];

for i=1:100
    [Q,R]=qr(A);
    A=R*Q
    pause
end


    





