% Define a quadratic functional by Q(x) = || Ax-b ||^2 as a function. 
% Here x and b are 2-dimensional vectors.
%
% Arguments:
% x1  horizontal coordinate of evaluation point, can be a matrix
% x2  vertical coordinate of evaluation point, can be matrix
% A   nx2 matrix
% b   vertical n-vector
%
% Returns
% Q   the value of Q, a real number
%
% Samuli Siltanen November 2015

function Q = Qfunctional(x1,x2,A,b)

% Test for size of arguments
[row1,col1] = size(x1);
[row2,col2] = size(x2);
if (~(row1==row2))|~((col1==col2))
    error('The size of x1 differs from size of x2')
end
if ~(size(A,2)==2)
    error('The matrix A must have 2 columns')
end
if (~(size(b,1)==size(A,1)))
    error('The size of b is not compatible with A')
end

% Evaluate Q
x1   = x1(:);
x2   = x2(:);
xmat = [x1.';x2.'];
Q    = sum((A*xmat-repmat(b,1,size(xmat,2))).^2);
Q    = reshape(Q,[row1,col1]);



