% Exampe of curve fit using 3rd order polynomial

%1) Generate data
x=0.1:0.1:2; X=x'; N=length(X);
Y=2*log(X)+5+randn(N,1)*0.2;

%2) Fit X and Y data to 3rd order polynomial using polyfit
p=polyfit(X,Y,3);   % Coefficients in 3rd order polynomial

Yb=polyval(p,X);    % The predictions

% OLS with correct model structure
X2=[log(X) ones(N,1)];
B=inv(X2'*X2)*X2'*Y;
Yb2=X2*B;

%4) Plot data
plot(X,Y,'-*',X,Yb,'--o',X,Yb,'--v')
legend('True data','3rd order polynomial','y=a*ln(x)+b structure')
xlabel('x data: 0.1 \leq x \leq 2') 
ylabel('y data')
title('Observations of x_k and y_k data')
grid


% Test. Using OLS method
Xd=[X.^3 X.^2 X ones(20,1)];
B3=inv(Xd'*Xd)*Xd'*Y         % The polynimial coefficients
Yb3=Xd*B3                    % The predictions