function randLineFit(ns,slope,intercept)
% randLineFit  Randomly select slope and intercept to fit a line to data

if nargin<1, ns=200;            end
if nargin<2, slope=1;           end
if nargin<3, intercept = 0.05;  end

% -- Plot data set
x = 1:8;
y = [4.41  6.82  7.07  12.02  13.97 20.77 20.87  25.17];
gray = [0.7 0.7 0.7];
plot(x,y,'.','MarkerSize',18,'Color',gray)
axis([0 10 0 30]);
hold('on')

% -- Generate a list of random slope and intercept values based on
%    user's guess at slope and intercept
slopeRand     = slope + 2*randn(ns,1);
interceptRand = intercept + 2*randn(ns,1);

% -- Set first guess at first random slope and intercept
ybest = zeros(size(y)); %  Will be replaced by better set of y values
rsave = zeros(ns,1);    %  vector to store residuals
kbest = 0;              %  Index of best random slope & intercept
nreplaced = 0;          %  Number of times best guess is replaced
minr = 1e6;             %  Guarantee that 1st guess will be minimum residual

for i=1:ns

  % -- Evaluate next guess line at given data points
  ytest_points = slopeRand(i)*x + interceptRand(i);
  
  % -- Use L2 norm to measure difference between y values from this
  %    guess and the y values
  
  r = %% INSERT code to compute L2 norm of residual

  rsave(i) = r; 

  % -- Save the line with smallest norm and update best guess line
  %    with the new line if it is has the current smallest norm
  
%   if %% INSERT test to determine whether current residual is minimum
% 
%     minr = r;
%     kbest = i;
%     nreplaced = nreplaced + 1;
%     ybest = ytest_points;
% 
%   end

end

fprintf('\nAfter %d tries and %d replacements\n',ns,nreplaced);
fprintf('the best random fit has residual = %12.3e\n',rsave(kbest));

% -- Add the best fit from random testing to the plot
plot(x,ybest,'b:')

% -- Add the least squares fit, which is the true best fit
c = polyfit(x,y,1);
xfit = [min(x) max(x)];
yfit = polyval(c,xfit);
plot(xfit,yfit,'r--');
hold('off')
rfit = norm( y - polyval(c,x) );
fprintf('Least squares fit has residual   = %12.3e\n',rfit);

% -- 3D Scatter plot of residual as function of random slope and intercept
figure('Name','3D scatter plot of residuals')
scatter3(slopeRand,interceptRand,rsave)
hold('on')
scatter3(slopeRand(kbest),interceptRand(kbest),rsave(kbest),'filled')
xlabel('Slope')
ylabel('Intercept')
hold('off')

end