% This is an example illustrating the use of quadprog to solve a simple linear
% system of equations with a single inequality constraint.
%
% Suppose the following needs to be solved
%
%     Ux = y, with the constraint x >= 1.
% 
% where U = [1 0; 0 1; 1 1; 1 -1], x = [x1, x2]' (unknown) and y = [1, 2, 3, 4]'.
% The constraint x >= 1 is a short way of writing [x1, x2] >= [1 1].
% 
% Since a solution is not always guaranteed to exist, we will solve it in the
% least squares sense, i.e., minimize the least square error:
%     
%                      (Ux - y)'(Ux - y) = x'(U'U)x - 2y'Ux + y'y
% with the constraint  x >= 1
%
% This can be done with the help of quadprog function. It might help to do 'help
% quadprog' before trying the code below.

U = [1 0; 0 1; 1 1; 1 -1];
y = [1, 2, 3, 4]';

% The following uses notation from 'help quadprog'. Note the scaling of the
% optimization function by 1/2 and that the last term (y'y) is a constant, which
% can be ignored for minimization.

H = U'*U;
f = -y'*U;
A = [-1 0; 0 -1];
b = [-1, -1]';

x = quadprog(H, f, A, b)

