function regress0

% fitting poly g(x) = v1 + v2*x + ... + vm*x^(m-1) to data
% for a < x < b

m=2
a=0;
b=6;

% icase = 1: solve normal equations to find v
% icase = 2: use built-in MATLAB commands for finding v
icase=1

%  generate (random) data for fitting
%  data points are randomly placed near curve y=f(x)
nd=40;
xd=a+(b-a)*rand(nd,1);
yd=zeros(nd,1);
for i=1:nd
    fd(i)=f(xd(i));
end
r=0.3*norm(fd,inf)*(rand(nd,1)-0.5);
for i=1:nd
    yd(i)=f(xd(i))+r(i);
end

% find v
if icase==1
    A=ones(nd,1);
    for im=1:m-1
        A=[A xd.^im];
    end
    M=A'*A; B=A'*yd;
    v=M\B;
    % next command needed to use polyval
    v=flip(v);
else
    v=polyfit(xd,yd,m-1);
end

% evaluate model function for plotting
N = 100;
X = linspace(a,b,N);
Y = polyval(v,X);

% plot results
clf
co = [0 0 1;
    0 0.5 0;
    1 0 0;
    0 0.75 0.75;
    0.75 0 0.75;
    0.75 0.75 0;
    0.25 0.25 0.25];
set(groot,'defaultAxesColorOrder',co)
% get(gcf)
set(gcf,'Position', [25 1115 658 230])

plot(xd,yd,'.','MarkerSize',20)
hold on
xlabel('x-axis')
ylabel('y-axis')
grid on
set(gca,'FontSize',16,'FontWeight','bold')
axis manual;

pause

plot(X,Y,'r','LineWidth',1.1)
hold off


function h=f(x)
h=1+2*x;
%h=sin(x);


















