%% Week 5
% Matlab codes for week 5

%% Problem 1

format rat
A=[1/10000,1;1,1]
[L,U,P]=lu(A)

%% Problem 2

format rat
A=[4,2,1;2,17,13/2;1,13/2,23/2];
lu(A)
chol(A)

%% Problem 4

format rat
A=[4,2,1;2,17,13/2;1,13/2,23/2];
b=[3;-9/2;-21/2];
G=chol(A); G=G'
y=G\b
x=G'\y

%% Problem 5

format long
A=[-1,5,-2;1,1,-4;4,-1,2]
b=[5;1;-1]

L=-tril(A,-1)
R=-triu(A,1)
D=diag(diag(A))

x=zeros(3,1); % initial vector
for i=1:25
    pause(0.3)
    i
    x=x % modify according to the method
end

%% Problem 6

% Computation of the optimal omega parameter

A=[2,-1;-1,2], b=[1;3]

syms omega

L=-tril(A,-1)
R=-triu(A,1)
D=diag(diag(A))

B=(1/omega*D)\(L+R+(1-omega)/omega*D)
f=((1/omega)*D)\b
eigenvalues=eig(B) % Eigenvalues of the iteration matrix

o=0:0.05:2;
plot(o,max(abs([1-o/2;1-3*o/2]))) % graph of the spectral radius against omega

%%

% Checking the convergence speed

x_exact=A\b;

omega=1
Bomega=eval(B);
fomega=eval(f);

x=zeros(2,1); % initial vector

i=0;
while norm(x-x_exact)>=10^-6
    i=i+1
    x=Bomega*x+fomega 
end

eigenvalues_omega=eval(eigenvalues)

