% Polynomial Fitting & Cost function
clc; clear all;
close all;

%plot the sine wave function by taking random samples
a=-1; b=1;
x = a + (b-a).*rand(10000,1);
%x=[0:0.1:pi]
y=sin(2*pi*x);
plot(x,y,'c.')
clear x y;
hold on

%plot samples of function
M=5; %M=number of weights
N=100; %N=number of samples
%x=[0:0.1:pi]
x = a + (b-a).*rand(N,1);
F=sin(2*pi*x);
plot(x,F,'ro')
grid on
hold on

%Fit a polynomial to approximate the sine wave
p=polyfit(x,F,M);
approx_model=polyval(p,x);
plot(x,approx_model,'b*')

legend('sin(2ðx)','real','approximation') % plot legend

%Calculate the cost function
cost_function=0;
for i=1:length(F)
    cost_function=cost_function+(F(i)-approx_function(i))^2;
end
cost_function=cost_function/2;

fprintf('\nCost Function:%.4f',cost_function);
