### 2.77 Determine if a set of linear equations A x= b has a solution and what type of solution

Problem: Given a general non homogeneous set of linear equations $$Ax=b$$ how to test if it has no solution (inconsistent), or one unique solution, or an inﬁnity number of solutions?

The following algorithm summarizes all the cases

Let [A|b] be the augmented matrix, where b is appended to A.

Assume A is an M by N matrix. i.e. M equations and N unknowns.

IF rank A < rank [A|b]  THEN  -- system is inconsistent
-- NO exact solution exist, but can use least square approximation

x= A/b  -- Matlab.
x= PseudoInverse[A].b  -- Mathematica uses SVD to computer pseduoInverse

ELSE -- we must have rank A == rank[A|b]  -- system is consistent
IF rank(A) == N  -- we have one solution.
IF M==N -- one unique solution, can use crammer rule.
x=A/b  -- Matlab. Here we get exact solution from \ operator
x=LinearSolve[A,b] -- Mathematica
ELSE  -- infinite solutions, pick one.
x=A/b  -- Matlab. Here we get exact solution from \ operator
x=LinearSolve[A,b] -- Mathematica
END
ELSE
-- rank A  < N, i.e. rank deficient, infinite solutions. will pick one
x=A/b
x=LinearSolve[A,b]
END
END

Let the system of equations be \begin {align*} y & =x-1\\ y & =2x+1 \end {align*}

So $A=\left ( {\begin {array} [c]{cc}1 & 1\\ -2 & 1 \end {array}} \right )$ and $b=\left ( {\begin {array} [c]{c}1\\ -1 \end {array}} \right )$

Mathematica

Remove["Global*"];
ContourPlot[{y==x-1,y==2 x+1} ,
{x,-3,2},{y,-6,3},
ContourStyle->{{Red,Thickness[0.01]},
{Blue,Thickness[0.01]}},
GridLinesStyle->Dashed,
ImageSize->300]



a = {{-2,1},{-1,1}};
b = {1,-1};
{nRow, nCol} = Dimensions[a];
aRank=MatrixRank[a]

2


abRank=MatrixRank[Insert[a,b,-1]]

2



The above algorithm can now be run as follows

If[aRank<abRank,
Print["System is no consistent, no exact solution"];
x=PseudoInverse[a].b,
If[aRank==nCol,
Print["System is consistent. Exact solution."];
x=LinearSolve[a,b]
,
Print["consistent, rank deficient,infinite solutions"];
x=LinearSolve[a,b]
]
];

Print["Solution is x=",x];



The output of the above is

System is consistent. Exact solution.
Solution is x={-2,-3}



Matlab

A=[-2 1;-1 1];
b=[1; -1];

[nRow,nCol]=size(A);
aRank=rank(A);
abRank=rank([A b]);

fprintf('A rank=%d, [A b] rank=%d\n',aRank,abRank);
fprintf('Number of unknowns=%d\n',nCol);

x=A\b;

if aRank<abRank
fprintf('System not consistent. no exact solution\n');
else
if aRank==nCol
fprintf('System consistent. Exact solution.\n');
else
fprintf('consistent,rank deficient,infinite solutions\n');
end
end

fprintf('solution is\n');
x



Output is

A rank=2, [A b] rank=2
Number of unknowns=2

System is consistent. Exact solution.
solution is
x =
-2
-3

`