clear;
format long;
close all;
 filename1='ex1.eps';
 filename2='ex1.txt';
  filename3='ex1.tex';
 write=fopen(filename2,'w');
  write_tex=fopen(filename3,'w');
N_loop=[10 20 40 80 160];
% table headings:
disp(' ')
disp('   N          D+           Order         D0           Order')
fprintf(write,'   N          D+           Order         D0           Order\n');
 fprintf(write_tex,'\\begin{tabular}{|c|c|c|c|c|} \n');
 fprintf(write_tex,'\\hline \n');
 fprintf(write_tex,'   N&          D+ &          Order  &       D0   &        Order\\\\ \\hline\n');
for jj=1:length(N_loop)
N=N_loop(jj);
h=(1-0)/N;
%There are many ways to discretize x
%method 1
% for ii=1:N+1
% x(ii)=0+(ii-1)*h;
% end
%method 2
%x=[0:h:1];
%method 3
x=linspace(0,1,N+1);
for ii=2:N
Dpu=(fun(x(ii+1))-fun(x(ii)))/(h);
Epu(ii)=abs(Dpu-dfun(x(ii)));
%Dmu=(fun(x)-fun(x-h))/h;
%Emu(ii)=Dmu-dfun(1);
Dou=(fun(x(ii+1))-fun(x(ii-1)))/(2*h);
Eou(ii)=abs(Dou-dfun(x(ii)));
end
%max-norm
maxpu(jj)=max(Epu);
maxou(jj)=max(Eou);

% %2-norm
% sum_p=0;
% sum_o=0;
% for ii=2:N
% sum_p=sum_p+Epu(ii)^2;
% sum_o=sum_o+Eou(ii)^2;
% end
% maxpu(jj)=sqrt(h*sum_p);
% maxou(jj)=sqrt(h*sum_o);

%Calculate the order of the methods
if (jj ==1)  
   ordmp(jj)=0;
   ordmo(jj)=0;
else
    ordmp(jj)=log(maxpu(jj)/maxpu(1))/log(N_loop(1)/N_loop(jj));
    ordmo(jj)=log(maxou(jj)/maxou(1))/log(N_loop(1)/N_loop(jj));
end
        
    % print line of table:
   disp(sprintf(' %4d  %15.6e  %8.4f  %15.6e  %8.4f',...
       N,maxpu(jj),ordmp(jj),maxou(jj),ordmo(jj)));
fprintf(write,' %4d  %15.6e  %8.4f  %15.6e  %8.4f \n',...
       N,maxpu(jj),ordmp(jj),maxou(jj),ordmo(jj));
    fprintf(write_tex,' %4d & %15.6e & %8.4f & %15.6e & %8.4f \\\\ \\hline\n',...
        N,maxpu(jj),ordmp(jj),maxou(jj),ordmo(jj));
end


loglog(1./N_loop,maxpu,'.-');
hold on;
loglog(1./N_loop,maxou,'o-');

        legend('Dpu','Dou');
        xlabel('h')
        ylabel('Error')
        title('u^{(1)}(x)')
        set(gca,'FontSize',18)
            fprintf(write_tex,' \\end{tabular}');
        fclose(write);
                fclose(write_tex);
 saveas(gcf,filename1);