%% Solve System of Equations
% Consider a linear system of equations with four equations and three unknowns.
% \begin{array}{l}
% x_1 +x_2 +5x_3 =6\\
% 2x_1 +x_2 +8x_3 =8\\
% x_1 +2x_2 +7x_3 =10\\
% -x_1 +x_2 -x_3 =2\ldotp
% \end{array}
% Create an augmented matrix that represents the system of equations.

A = [1  1  5;
     2  1  8;
     1  2  7;
    -1  1 -1];
b = [6 8 10 2]';
M = [A b];

%
% Use rref to express the system in reduced row echelon form.

R = rref(M)

%
% The first two rows of R contain equations that express x_1 and x_2 in terms of x_3. The second two rows imply that there exists at least one solution that fits the right-hand side vector (otherwise one of the equations would read 1=0). The third column does not contain a pivot, so x_3 is an independent variable. Therefore, there are infinitely many solutions for x_1 and x_2, and x_3 can be chosen freely.
% \begin{array}{l}
% x_1 =2-3x_3 \\
% x_2 =4-2x_3 \ldotp
% \end{array}
% For example, if x_3 =1, then x_1 =-1 and x_2 =2.
%
% From a numerical standpoint, a more efficient way to solve this system of equations is with x0 = A\b, which (for a rectangular matrix A) calculates the least-squares solution. In that case, you can check the accuracy of the solution with norm(A*x0-b)/norm(b) and the uniqueness of the solution by checking if rank(A) is equal to the number of unknowns. If more than one solution exists, then they all have the form of x=x_0 +\textrm{nt}, where n is the null space null(A) and t can be chosen freely.
%
% Copyright 2018 The MathWorks, Inc.