%% Weeks 3-4
% Matlab codes for weeks 3-4

%% Problem 1

A=toeplitz([2,-1,0,0]);

%% Problem 5

A=toeplitz([3,-1,-1,0]);
b=[1;1;1;1];
Atilde=A+(0.04*rand(4)-0.02);
x=A\b
xtilde=Atilde\b
rel_error=norm(x-xtilde,inf)/norm(x,inf)

%% Problem 6

A=[34,55;55,89];
b=[21;34];
x1=[-0.11;0.45];
x2=[-0.99,1.01];

%% Problem 7

A=[1,1,1;2,4,4;-1,5,8];
b=[4,14,17];

% Code for the LU decomposition
% The code rewrites A with L and U

[n,n] = size(A);
tol = 1.e-6;

for k = 1:n-1
   if abs(A(k,k)) < tol
      disp(['Small pivot encountered in column ' int2str(k)])
   end
   for i = k+1:n
      A(i,k) = A(i,k)/A(k,k);
      A(i,k+1:n) = A(i,k+1:n) - A(i,k)*A(k,k+1:n);
   end
end

U=triu(A)
L=eye(n)+tril(A,-1)
