% FILE: hlp111.m begin
% This is a simplified version  of e626.m
% Suppose phi(k,x) is a lin. independent system, k=1,...,n
% The program gives the Least Squares approximation of
% a given function f

close all

set(0,'DefaultAxesFontWeight','bold')

a=-1; b=2;
%  Define the function f:

myf=@(x) (sin(3*x)+x.^2);
% Define the system phi(k,x):
phi=@(k,x)( x.^k);
% For several values of n, form the LSQ-approximation
% in terms of phi(k,x), j=1,...,n
for n=2:5
LHS=zeros(n,n);
rhs=zeros(n,1);
for j=1:n
h1=@(x)phi(j,x);
	for k=1:j
	     	
	      h2=@(x)(phi(k,x).*h1(x));
              LHS(j,k)=quad(h2,a,b,10^(-12));
	      LHS(k,j)=LHS(j,k);
              h3=@(x)(myf(x).*phi(k,x));
              rhs(k,1)=quad(h3,a,b, 10^(-12));
end
end

			    cst=LHS\rhs;
			    fprintf('---------\n n= %2d\n cst= ',n);
			    disp(cst')

figure(n)

x=a:0.01*(b-a):b;
y1=myf(x);
y2=0*x;
for k=1:n
y2=y2+cst(k,1)*phi(k,x);
end

plot(x,y1,'k-', x,y2,'b-.','LineWidth',2)
text(  0, 2,['n=' num2str(n)],'FontSize',20,'FontWeight','bold')
grid
pause(2)

end



% FILE: hlp111.m end


