%%
%iterative methods of linear systems solving

%Jacobi method
A = [4 1 -2; 2 5 2; 1 1 -5]
b = [4;5;4]

    %upper triangular matrix with zeros on diagonal
U=triu(A,1)
    %lower triangular matrix with zeros on diagonal
L=tril(A,-1)
    %diagonal matrix
D=A-U-L
    %matrix M (transformed matrix A)
MJ=(-1)*inv(D)*(U+L)
    %vector v (transformed vector b)
vJ=inv(D)*b 
    %initial estimation
x0 = [0;0;0]
    %first iteration
x1=MJ*x0+vJ
    %second iteration
x2=MJ*x1+vJ 
%number of iterations needed for precise caclulation is 11 (see below)


%Gauss-Seidel method
    %matrix M (transformed matrix A)
MG=(-1)*inv(D+L)*U
    %vector v (transformed vector b)
vG=inv(D+L)*b 
    %initial estimation
x0 = [0;0;0]
    %first iteration
x1=MG*x0+vG
    %second iteration
x2=MG*x1+vG
%%

%Jacobi method using function
    %function calculating individual iterations using Jacobi method
jacobi_func = @(x) MJ*x+vJ

    %using limited number of iterations (for cycle)
solution = x0   %initial estimation
for i = 1:10    %maximum 10 iterations
   solution = jacobi_func(solution) %solution of new iteration
   i    %number of iterations for convergence
end

    %condition for the difference(norm) knowing the true value (while cycle)
true_solution = A\b %real (true) solution

j = 0   %initial number of iterations is zero
solution_2 = x0 %initial estimation
while norm(true_solution-solution_2) > 10^(-4) %calculate new iterations until the difference is not greater than 10^(-4), i.e., the difference is lower or equal to 10^(-4)
   solution_2 = jacobi_func(solution_2)        %solution of new iteration
   j = j+1                                     %number of iterations
end

norm(true_solution-solution_2)              %difference between iteration solution and real solution
j   %number of iterations needed

%Gauss-Seidel method using function
    %function calculating individual iterations using Jacobi method
gauss_seidel_func = @(x) MG*x+vG

    %using limited number of iterations (for cycle)
solution = x0   %initial estimation
for i = 1:10    %maximum 10 iterations
   solution = gauss_seidel_func(solution) %solution of new iteration
end

    %condition for the difference(norm) knowing the true value (while cycle)
true_solution = A\b %real (true) solution

j = 0   %initial number of iterations is zero
solution_2 = x0 %initial estimation
while norm(true_solution-solution_2) > 10^(-4) %calculate new iterations until the difference is not greater than 10^(-4), i.e., the difference is lower or equal to 10^(-4)
   solution_2 = gauss_seidel_func(solution_2);  %solution of new iteration
   j = j+1;                                     %number of iterations
end

norm(true_solution-solution_2) %difference between iteration solution and real solution
j   %number of iterations needed for convergence
