
function demo_integrazione0(example)

N=1:10;
N=1;
do_table=1;
do_plot=1;
Nplot=4;

if nargin < 1
    example=2;
end

switch example
    case 0
        a=0.5; b=2; f=@(x) sin(x); sol=-cos(b)+cos(a);
    case 1
        a=-1; b=1; f=@(x) exp(x); sol=exp(b)-exp(a);
    case 2
        a=-1; b=1; f=@(x) cos(x); sol=sin(b)-sin(a);
    case 3
        a=0; b=pi/2; f=@(x) (x.^2+x+1).*cos(x); sol=-2+pi/2+pi^2/4;
    case 4
        a=0; b=2*pi; f=@(x) 3+sin(2*x)+cos(x)+x;
        pp=chebfun(f,[a,b]); sol=sum(pp);
end


% --------------------- code starts here ---------------------

if do_table == 1
    
    % trapezi composte
    for ii=1:length(N)
        [x,w]=rettangolo(N(ii),a,b);
        fx=feval(f,x);
        I(ii,1)=w'*fx;
    end
    
    for ii=1:length(N)
        fprintf('$%2.0f$ & ',N(ii))
        if isnan(I(ii,1)) == 1
            fprintf('$$ &');
        else
            fprintf('$%1.1e$ &',abs(I(ii,1)-sol));
        end
        fprintf(' \\\\\n \t');
    end
    
    fprintf('\n \n');
    
end

if do_plot == 1
    [x,w]=rettangolo(Nplot,a,b);
    y=feval(f,x);
    clf;
    xt=linspace(a,b,1000);
    yt=feval(f,xt);

    hold on;
    m=min(yt); M=max(yt);
    plot([a a a-10^(-2) b+10^(-2)],[0.9*m 1.1*M 0 0],'w.');
    plot(x,zeros(size(x)),'ro');
    plot([a a],[0 feval(f,a)],'k--');
    plot([b b],[0 feval(f,b)],'k--');
    
    subs=Nplot;
    h=(b-a)/Nplot;
    for jj=1:subs
        
        aa=a+(jj-1)*h;
        bb=a+jj*h;
        xx=linspace(aa,bb,1000);
        
        xs=x(jj);
        ys=y(jj);
        ps=polyfit(xs,ys,0);
        yy=polyval(ps,xx);
        
        
        
        plot(xx,yy,'r-','LineWidth',2,...
            'MarkerEdgeColor','k',...
            'MarkerFaceColor','k',...
            'MarkerSize',10);
        X=[aa bb fliplr(xx) aa];
        Y=[0 0 fliplr(yy) 0];
        
        fill(X,Y,'c')
        
    end
    
        plot(xt,yt,'k-','LineWidth',2,...
        'MarkerEdgeColor','k',...
        'MarkerFaceColor','k',...
        'MarkerSize',10)
    hold off
end




function [x,w]=rettangolo(N,a,b)
% FORMULA DI SIMPSON COMPOSTA.
% INPUT:
% N: NUMERO SUBINTERVALLI.
% a, b: ESTREMI DI INTEGRAZIONE.
% OUTPUT:
% x: INTEGRAZIONE.
% w: PESI INTEGRAZIONE (INCLUDE IL PASSO!).
h=(b-a)/N;             % AMPIEZZA INTERVALLO.
x=a:h:b; x=(x(1:end-1))';     % NODI INTEGRAZIONE.
w=h*ones(length(x),1);           % PESI INTEGRAZIONE.


