%{ 
MATH3290 Tutorial2_code.m
TANG Shiqi 
March 9, 2020

Since you may use MATLAB to solve high-dimension linear system quite
often in tutorial2, so here is guidance for you if you are not familiar
with programming by MATLAB. I hope that can help. :D
%}


%%%%%%%%%%   Solving linear system: Method 1  %%%%%%%%%% 
% For example2 in tutorial2, if we already have the following equations:
% a_1 - 2b_1 + 4c_1 - 8d_1 = 20
% a_1 = 25
% a_2 = 25
% a_2 + 3b_2 + 9c_2 + 27d_2 = 5
% b1 - b2 = 0
% 2c_1 - 2c_2 = 0
% c_1 - 6d_1 = 0
% c_2 - 9d_2 = 0

% Since we already have 8 equations, so that we can determine 
%the value of a_1, b_1, c_1, d_1, a_2, b_2, c_2, d_2.

% Then we can see, it is just a linear system in form of AX=b
% A is the coefficient matrix, and X is a column vector containing all
% variables. 

A = [1 -2 4 -8 0 0 0 0;
    1 0 0 0 0 0 0 0;
    0 0 0 0 1 0 0 0;
    0 0 0 0 1 3 9 27;
    0 1 0 0 0 -1 0 0;
    0 0 2 0 0 0 -2 0;
    0 0 1 -6 0 0 0 0;
    0 0 0 0 0 0 1 9];

b = [20; 25; 25; 5; 0; 0; 0; 0];

format rat % this is for using rational representation

X = A\b; % Here, X = [a_1; b_1; c_1; d_1; a_2; b_2; c_2; d_2]

% So now we can have the values the 8 variables.


%%%%%%%%%%   Solving linear system: Method 2  %%%%%%%%%% 
% We can also use 'rref' to solve linear system.
% We also use example2 in tutorial2 here.
% From above content, to solve AX=b we already have

A = [1 -2 4 -8 0 0 0 0;
    1 0 0 0 0 0 0 0;
    0 0 0 0 1 0 0 0;
    0 0 0 0 1 3 9 27;
    0 1 0 0 0 -1 0 0;
    0 0 2 0 0 0 -2 0;
    0 0 1 -6 0 0 0 0;
    0 0 0 0 0 0 1 9];

b = [20; 25; 25; 5; 0; 0; 0; 0];

% Remember that: in linear algebra, to find the inverse of matrix, we 
% follow these steps: Using elementary operators, transform matrix to 
% its reduced row echelon form. 
% Function 'rref' is produces the reduced row echelon form of matrix.

format rat % this is for using rational representation
Y = [A b]; % Y is augmented matrix
rref(Y);

% 8 elements are: a_1, b_1, c_1, d_1, a_2, b_2, c_2, d_2 respectively.


%%%%%%%%%%   Warning  %%%%%%%%%% 
% Try NOT to use 'inv' function to take inverse of matrix
% Some times 'inv' may take long execution time and get terrible 
% numerical accuracy.
% So use the matrix backslash operator.