figure
hold on

% plot noisy sample data
xSamples = linspace(-1,1,15);
f = @(x) 3 * x .^ 3 + 2 * x .^ 2+ x- 5;
fSamples = f(xSamples) + (rand(1,length(xSamples))-.5)*2;
scatter(xSamples,fSamples,'MarkerFaceColor','b');

% use Matlab to fit data
input('Hit Enter to do polynomial fit');
coeffs = polyfit(xSamples,fSamples,3)
fFit = @(x) polyval(coeffs,x); % create a function handle for conveniently evaluating the fit polynomial
xFine = linspace(-1,1,100);
plot(xFine, fFit(xFine),'--b');

% plot residuals
input('Hit Enter to show residuals');
for i = 1:length(xSamples)
    xArray = [xSamples(i),xSamples(i)];
    yArray = [fFit(xSamples(i)),fSamples(i)];
    plot(xArray,yArray,'r');
end


hold off;