function LeastSquaresDegreeN(t,b,n)
% usage:  t is independent variable vector, b is function data
% n is degree of desired best fit polynomial
% i.e., b = f(t)
% Try t = -2.6:0.005:1.8 with NinthDegreeTestData.dat
% and t = -2.5:0.025:4.5 with ForthDegreeTestData.dat

dataSize = length(b);
A = zeros(dataSize,n);

% Given basis phi(t) = 1 + t + t^2 + ... + t^n
% Initialize A
A(1:dataSize,1) = 1;
% Fill in the rest of A
for i = 1:1:n
    A(1:dataSize,i+1) = (t(1,1:dataSize)).^(i);
end

b = b';
[Q,R] = qr(A);
c = Q'*b;
x = R\c;

% initialize xPlot with the right starting value
xPlot = x(1,1);
% create the rest of the entries
for i = 1:1:n
    xPlot = xPlot + x(i+1,1)*(t(1:dataSize)).^i;
end

% Third Degree Polynomial
% x(1,1) + x(2,1)*t(1:size_plot) + x(3,1)*(t(1:size_plot)).^2 + x(4,1)*(t(1:size_plot)).^3

plot(t(1:dataSize),b(1:dataSize),'r*',t(1:dataSize), xPlot,'k')
title('Data plotted with Nth Degree Least Squares Polynomial', 'FontWeight', 'bold', 'Color', 'b', 'FontSize', 14)
xlabel('independent variable t', 'FontWeight', 'bold', 'FontSize', 12)
ylabel('function values f(t)', 'FontWeight', 'bold', 'FontSize', 12)
legend('Input Data', 'Nth Degree Polynomial')
axis tight

% For debugging:
% length(t);
% length(b);

% Check
Soln = A\b
Resid = Soln - x

% Code by Eric Johnson -- Focus | Numeric
end