%We choose an interval
x=-5:5
%Function values at these points
y=[0,0,0,1,1,1,0,0,0,0,0]
%Build the Vandermonde matrix
V=fliplr(vander(x));
%Find the coeffcients of the interpolating polynomial
c=V\y';
xx=linspace(-5,5,200);
X=xx'*ones(1,11);
for j=1:200
X(j,:)=X(j,:).^(0:10);
end
%Evaluate the interpolating polynomial at intermediate points
%and plot the result
yy=X*c;
figure, plot(xx,yy,x,y,'b*')
pause
%We now take submatrices of V and compute the least squares approximate
%solution
%Choose a degree
n=9
Vs=V(:,1:n+1);
cs=Vs\y'
yys=X(:,1:n+1)*cs;
figure, plot(xx,yy,xx,yys,x,y,'b*')
title(['degree = ',num2str(n),' and 11.'])
