
% Fitting a polynomial to data
% Ricardo Carretero Nov'2004

format compact
lw=1;

% data on a line
a=0.5;
b=0.1;
x=0:0.1:10;
y0=a*x+b;

% adding noise
N=length(x);
rng('default'); % for reproducibility: ALWAYS reset the random generator
noise=(rand(1,N)-0.55);
y=y0+1.0*noise;

% fit a polynomial of degree 1
degree=1;
[coeff,temp]=polyfit(x,y,degree);
coeff
yfit=coeff(1)*x+coeff(2);

% plot
figure(1);clf
plot(x,y,'+b','LineWidth',lw)
hold on
plot(x,y0,'--k','LineWidth',lw)
plot(x,yfit,'-r','LineWidth',lw)
xlabel('x');
ylabel('y');
leg=legend('noisy data','original line','fitted line','Location','NW');
set(gca,'FontSize',18)
set(leg,'FontSize',18)
axis tight

