
function demo_integrazione1(example)

N=4;

do_table=1;
do_plot=1;
Nplot=5;

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]=trapezi_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]=trapezi_composta(Nplot,a,b);
    y=feval(f,x);
    
    xt=linspace(a,b,1000);
    yt=feval(f,xt);
    
    m=min(yt); M=max(yt);
    
    X=[a b fliplr(x') a];
    Y=[0 0 fliplr(y') 0];
    
    clf;
    fill(X,Y,'c');
    hold on;
    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(x,y,'r-','LineWidth',2,...
        'MarkerEdgeColor','k',...
        'MarkerFaceColor','k',...
        'MarkerSize',10);
    
    plot(xt,yt,'k-','LineWidth',2,...
        'MarkerEdgeColor','k',...
        'MarkerFaceColor','k',...
        'MarkerSize',10)
    hold off
end




function [x,w]=trapezi_composta(N,a,b)

% FORMULA DEI TRAPEZI COMPOSTA.

% INPUT:
% N: NUMERO SUBINTERVALLI.
% a, b: ESTREMI DI INTEGRAZIONE.

% OUTPUT:
% x: NODI INTEGRAZIONE.
% w: PESI INTEGRAZIONE (INCLUDE IL PASSO!).

h=(b-a)/N;             % PASSO INTEGRAZIONE.
x=a:h:b; x=x';         % NODI INTEGRAZIONE.
w=ones(N+1,1);         % PESI INTEGRAZIONE.
w(1)=0.5; w(N+1)=0.5;
w=w*h;

