
%2nd lab of scientific computing 2017/18

%linear regression
1==1;
function [a,b]=linreg(x,y)
%solves linear regression i.e .finds a,b s.t.
%they minimize \sum_k|a*x(k)+b-y(k)|^2
  if(rows(x)==1) x=x'; end
  if(rows(y)==1) y=y'; end
  n=length(x);
  A=ones(n,2);
  A(:,2)=x;
  s=A\y;
  a=s(2);b=s(1);
end  

x=randn(10,1);
y=2.3-5.6*x;

[a,b]=linreg(x,y)
y=2.3-5.6*x+randn(size(x))*1e-1;

[a,b]=linreg(x,y)



%polynomial interpolation
%Runge example
f=@(x) 1.0./(1+x.*x);
z=linspace(-5,5,300);
for n=3:20,
 x=linspace(-5,5,n+1)';
 A=vander(x);
 y=f(x);
 p=A\y; %p coeff of the Lagrange interpolant  
 plot(x,y,"+r;equid. pts;",z,f(z),"b;1/(1+x^2);",z,polyval(p,z),"g");
 pause(1);
 
end


%polynomial interpolation
%Runge example on Chebyshev points
f=@(x) 1.0./(1+x.*x);
a=-5;b=5;
z=linspace(a,b,300);
for n=3:20,
 x=(b+a)*0.5 + 0.5*(b-a)*cos(pi*(0.5+(0:n))/(n+1));
 A=vander(x);
 y=f(x');
 p=A\y; %p coeff of the Lagrange interpolant  
 plot(x,y,"+r;Cheb pts;",z,f(z),"b;1/(1+x^2);",z,polyval(p,z),"g");
 pause(1);
  
end