%%
%direct methods of linear systems solving
A1 = [1 2 2;2 2 3;-1 -1 0]
b = [2;5;-1]
x1 = A1 \ b %in-built function
x2 = inv(A1) * b %by inversion matrix
[L, U, P] = lu(A1) %LU decomposition of matrix A - stores particular matrices including permutation matrix
x3 = U \ ( L \ (P*b)) %solving by LU decomposition (solve L*y = P*b, U*x = y, where P is permutation matrix)
%Cholesky decompostion (symmetric positively definite matrix)
A = [4 -1 0; 2 3 -2; 0 -2 3];
sym_A = [4 2 0; 2 3 -2; 0 -2 3]; %symmetric matrix
chol(sym_A) %in-built function for Cholesky decomposition
transpose(chol(sym_A))*chol(sym_A) %recalculation of matrix sym_A
x4 = chol(sym_A)\(transpose(chol(sym_A))\b)
%calculation of U matrix using matrix V
A2 = [-1 2 0; 3 2 2;4 -5 2]
V = [1 0 0; 0 1 0; 4 0 1] %we choose the same number at the same position as matrix A2 (be careful, if the pivot is not -1 it will not work)
V*A2 %this will result into matrix with zero element on position (3,1) pivot point (diagonal point in column 1, i.e., position (1,1) is -1)
V1 = [1 0 0; 3 1 0; 0 0 1]
V1*(V*A2) %this will result into matrix with zeros on positions (3,1) and (2,1), pivot point is same
V2_bad = [1 0 0; 0 1 0; 0 3 1]
V2_bad*(V1*(V*A2)) %we wanted this to result into matrix with zeros on positions (3,1), (2,1), and (3,2) but (3,2) is not zero due to pivot point equal to 8, not -1
V2_good = [1 0 0; 0 1 0; 0 -3/8 1] %we have to divide the particular element by pivot value 8*(-1) to have there -1, i.e., 1/8*(-1)
U2 = V2_good*(V1*(V*A2)) % this is U matrix of matrix A2
L2 = inv(V)*inv(V1)*inv(V2_good) %this is L matrix of matrix A2
isequal(A2,L2*U2) %returns one if these two matrices are equal