%% Solve System of Linear Equations Using Pseudoinverse
% Compare solutions to a system of linear equations obtained by backslash (\) and pinv.
%
% If a rectangular coefficient matrix A is of low rank, then the least-squares problem of minimizing norm(A*x-b) has infinitely many solutions. Two solutions are returned by x1 = A\b and x2 = pinv(A)*b. The distinguishing properties of these solutions are that x1 has only rank(A) nonzero components, and norm(x2) is smaller than for any other solution.
% Create an 8-by-6 matrix that has rank(A) = 3.

A = magic(8); 
A = A(:,1:6) 

%
% Create a vector for the right-hand side of the system of equations.

b = 260*ones(8,1)

%
% The number chosen for the right-hand side, 260, is the value of the 8-by-8 magic sum for A. If A were still an 8-by-8 matrix, then one solution for x would be a vector of 1s. With only six columns, a solution exists since the equations are still consistent, but the solution is not all 1s. Since the matrix is of low rank, there are infinitely many solutions.
% Solve for two of the solutions using backslash and pinv.

x1 = A\b
x2 = pinv(A)*b

% Both of these solutions are exact, in the sense that norm(A*x1-b) and norm(A*x2-b) are on the order of roundoff error. The solution x1 is special because it has only three nonzero elements. The solution x2 is special because norm(x2) is smaller than it is for any other solution, including norm(x1).

norm(x1)
norm(x2)

%
% Copyright 2012 The MathWorks, Inc.