%% Solve a least squares problem with cvx
% based on cvx/examples/cvxbook/Ch06_approx_fitting/fig_6.5

%% Step 0
% Make sure you have cvx on your path and have run cvx_setup

%% Step 1
m=40;  n=2;    A = randn(m,n);
xex = [5;1];
pts = -10+20*rand(m,1);
A = [ones(m,1) pts];
b = A*xex + .5*randn(m,1);
outliers = [-9.5; 9];  outvals = [20; -15];
%%
A = [A; ones(length(outliers),1), outliers];
b = [b; outvals];
m = size(A,1);
pts = [pts;outliers];

% Least Squares
fprintf(1,'Computing the solution of the least-squares problem...');

cvx_begin 
  variable xls(n)
  minimize sum(huber(A*xls-b))
cvx_end

fprintf(1,'Done! \n');

%%
% Plots
figure(1);  hold off
plot(pts,b,'o', ...
     [-11; 11], [1 -11; 1 11]*xls, '--');
axis([-11 11 -20 25])
title('Least-square fit');
xlabel('x');
ylabel('y');