
function demo_integrazione2(example)

%N=1:10;
N=1;
do_table=1;
do_plot=1;
Nplot=3;

if nargin < 1
    example=4;
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
    
    % simpson composte
    for ii=1:length(N)
        [x,w]=simpson_composta(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]=simpson_composta(Nplot,a,b);
    y=feval(f,x);
    
    xt=linspace(a,b,1000); yt=feval(f,xt);
    m=min(yt); M=max(yt);
    
    clf;
    hold on;
    
    % disegno interpolante e area
    
    subs=Nplot;
    in=1; fin=3;
    for jj=1:subs
        ia=in;
        ib=fin;
        aa=x(ia); bb=x(ib);
        xx=linspace(aa,bb,1000);
        xs=x(ia:ib);
        ys=y(ia:ib);
        ps=polyfit(xs,ys,2);
        yy=polyval(ps,xx);
        plot(xx,yy,'r-','LineWidth',2,...
            'MarkerEdgeColor','r',...
            'MarkerFaceColor','r',...
            'MarkerSize',10);
        hold on;
        X=[aa bb fliplr(xx) aa];
        Y=[0 0 fliplr(yy) 0];
        fill(X,Y,'c');
        in=in+2; fin=fin+2;
    end
    
    plot([a a a-10^(-2) b+10^(-2)],[0.9*m 1.1*M 0 0],'w.');
    plot(x,zeros(size(x)),'ro');
        for ss=1:length(x)
        plot([x(ss) x(ss)],[0 feval(f,x(ss))],'k--')
        end
    
    plot(xt,yt,'k-','LineWidth',2,...
        'MarkerEdgeColor','k',...
        'MarkerFaceColor','k',...
        'MarkerSize',10)
    
    hold off
end




function [x,w]=simpson_composta(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/2):b; x=x';     % NODI INTEGRAZIONE.
w=ones(2*N+1,1);           % PESI INTEGRAZIONE.
w(3:2:2*N-1,1)=2*ones(length(3:2:2*N-1),1);
w(2:2:2*N,1)=4*ones(length(2:2:2*N),1);
w=w*h/6;

