function [ max_error, error_loc ] = example(n)
% example: an example Matlab file for CPSC 303
%
%   max_error = example(n)
%
% This function demonstrates a reasonable Matlab coding style as well as
% some functions useful when plotting results for black and white
% hardcopy.
%
% What it actually does is plot a very high resolution plot of sin(2*pi*x)
% over the interval [ -1, +1 ], and compares that plot with a plot
% containing n sample values.
%
% Input Parameters:
%
%   n - Number of samples in the coarse sampling.  Default = 21.
%
% Output Parameters:
%
%   max_error - Largest deviation between linear interpolation of the
%   coarse sampled function and the finely sampled function.
%
%   error_loc - The x value where the maximum error occurred.
%
% Ian Mitchell for CPSC 303, Homework 1, Question 0 (January 7, 2006)

  % Assign default inputs.
  if(nargin < 1)
    n = 21;
  end
  
  % What is a "high resolution" plot.
  big_number = 1e3;

  % What is our function?
  f = inline('sin(2 * pi * x)', 'x');
  
  % Get the high resolution sampling.
  big_xs = linspace(-1, +1, big_number);
  big_ys = feval(f, big_xs);

  % Get the low resolution sampling.
  if(n > big_number)
    warning('You have asked for a very high resolution sampling already');
  end
  n_xs = linspace(-1, +1, n);
  n_ys = feval(f, n_xs);
  
  % Create the plot.
  figure;
  % Capture the graphics handles so we can modify plot parameters.
  big_hs = plot(big_xs, big_ys, 'b-');
  hold on;
  n_hs = plot(n_xs, n_ys, 'r*:');
  
  % Make the lines thicker for output.
  set(big_hs, 'LineWidth', 2.0);
  set(n_hs, 'LineWidth', 2.0);
  
  % Label the plot.
  title(['Fine and Coarse Sampling of sin(2*\pi*x) - ' ...
         'Ian Mitchell for CPSC 303, HW 1, Q 0' ])
  xlabel('x');
  ylabel('sin(2 * \pi * x)');
  legend([ big_hs(1), n_hs(1) ], 'coarse', 'fine')

  % If necessary, find the maximum error.
  if(nargout > 0)
    
    % Compute the value of the linear interpolant of the coarse sampling
    % at each of the fine sampling's abscissae.
    n_interp = interp1(n_xs, n_ys, big_xs, 'linear');
    
    n_error = n_interp - big_ys;
    [ max_error, error_index ] = max(abs(n_error));
    error_loc = big_xs(error_index);
  end
  

