function p=l2_aproximace(x,f,stupen)
%
% Sestroji diskretni L2-aproximaci 
% pro funkci zadanou tabulkou [x;f(x)]
% pouzitim polynomu stupne stupen
%
% nejsou-li zadane vektory x,f => zadaji se mysi


clc;
pocet_deleni=1000;
presah=15;
barva=['r','m','g','b','k'];
styl=['- ';'--';'-.';': '];

if exist('stupen')==1 
  if stupen>max(size(x))-1
    stupen=max(size(x))-1;
    disp(' ');
    disp('Pozor! Stupen aproximujiciho polynomu musi byt mensi nez pocet zadanych bodu');
    disp(' ');
  end
end  
figure(1);
clf;
hold on;
zoom on;
set(figure(1),'Units','centimeters');
set(figure(1),'Position',[10 3 18 15]);

if exist('x')~=1 || exist('f')~=1 
  [x,f]=zadej_body;
  clc;
else
  plot(x,f,'ro');
  xmin=min(x);
  xmax=max(x);
  fmin=min(f);
  fmax=max(f);
  plot(x,f,'ro');
end  

[x,indexy]=sort(x);
f=f(indexy);
n=max(size(x));
deleni=(x(n)-x(1))/pocet_deleni;
zoom on;

disp('----------------------------------------------------------------------------');
if exist('stupen')==1
 fprintf('  Diskretni L2-aproximace polynomem stupne %2d\n',stupen);
else
 fprintf('  Diskretni L2-aproximace polynomy stupne 0 az %2d\n',n-1);
end  
fprintf('          pro funkci danou tabulkou\n');
disp(' ');
fprintf(' |    x(k)    |    f(k)    |\n');
fprintf(' ===========================\n');
for i=1:n
  fprintf(' | %9.4f  | %9.4f  |\n',x(i),f(i));
end  


xmin=x(1);
xmax=x(n);
xk=x(1)-presah/100*(xmax-xmin):deleni:x(n)+presah/100*(xmax-xmin);
if exist('stupen') 
 p=polyfit(x,f,stupen);  
 fk=polyval(p,xk);
 fmin=min([min(fk),min(f)]);
 fmax=max([max(fk),max(f)]);
else
 fmin=min(f);
 fmax=max(f);
 for i=0:n-1 
  p=polyfit(x,f,i);  
  fk=polyval(p,xk);
  fmin=min([min(fk),fmin]);
  fmax=max([max(fk),fmax]);
 end  
end  
 
 
set(figure(1),'Position',[7 3 32 15]);
clf;
hold on;
axis([xmin-2*presah/100*(xmax-xmin) xmax+2*presah/100*(xmax-xmin) ...
      fmin-presah/200*(fmax-fmin) fmax+presah/200*(fmax-fmin)]); 
plot(x,f,'ro');
popis=sprintf('Zadane body                             ');
texty(1,:)=popis(1:35); 
legend(texty,'Location','bestoutside');

disp(' ');
disp('Stiskni klavesu');
pause;

if exist('stupen') 
 plot(xk,fk,'b');
 popis=sprintf('L2-aproximace polynomem stupne %2d     ',stupen);
 texty(2,:)=popis(1:35); 
 legend(texty,'Location','bestoutside');
 text=['P_',num2str(stupen),'(x) = ',predpis_polynom(p)];
 disp(' ');
 disp(text);
 disp(' ');
else
 for i=0:n-1
  k=i+1; 
  color=strcat(barva(mod(k-1,5)+1),styl(mod(floor((k-1)/5),5)+1,:));
  p=polyfit(x,f,i);  
  fk=polyval(p,xk);
  plot(xk,fk,color);
  text=['P_',num2str(i),'(x) = ',predpis_polynom(p)];
  disp(' ');
  disp(text);
  if i==n-1
    popis=sprintf('Interpolace polynomem stupne %2d     ',i);
  else  
    popis=sprintf('L2-aproximace polynomem stupne %2d     ',i);
  end
  texty(i+2,:)=popis(1:35); 
  legend(texty,'Location','bestoutside');
  if i<n-1
    pause;
  else
    disp(' ');
  end 
 end 
end


