I have written a small matlab function to compute the trapezoidal integration. The function takes the function to be integrated, the limits, and the number of strips to use, and it outputs the integration result for successive value of number of strips used up to the maximum.

 

For example, for this problem, I asked it to compute the integral for n=4, this is the result:

 

>> nStrips=4; f='x*exp(2*x)'; from=0; to=3; v=nma_trapezoidal(f,from,to,nStrips)

 

v =

 

          1815.42957071731

          952.907243435826

          721.728546404322

          630.878480889609

 

The last row in the result, is the asnwer for n=4.

 

This below is a run for n=20

 

>> nStrips=30; f='x*exp(2*x)'; from=0; to=3; v=nma_trapezoidal(f,from,to,nStrips)

 

v =

          1815.42957071731

          952.907243435826

          721.728546404322

          630.878480889609

          586.718937655859

          562.124445229887

          547.079483006849

          537.225888423362

          530.429246311383

          525.546941631965

          521.923387644974

          519.160963777893

           517.00729763538

          515.296023313487

          513.913898807044

          512.781695188809

          511.842644620972

          511.055216268612

          510.388462738039

          509.818943070872

          509.328640480464

          508.903523764667

          508.532534744533

          508.206863471385

          507.919421428817

          507.664453265978

          507.437246953911

          507.233914859052

          507.051226580691

          506.886480026577

 

function v=nma_trapezoidal(func,from,to,nStrips)

%function r=nma_trapezoidal(f,from,to,nStrips)

%

% integrates a function using trapezoidal rule

%

% INPUT:

%   func : a string that repesents the function itself

%       for example 'x*sin(x)'. The independent variable

%       used in the string must be 'x' and no other letter.

%

%  from: lower limit

%  to  : upper limit

%  nStrips: number of strips to use

%

% OUTPUT

%   v : a column vector that represents the trapeziodal

%       intergation values. First row contains the

%       value of integration when using 1 strip. second

%       row for when using 2 strips, etc...

%

% Author: Nasser Abbasi

% May 3, 2003

 

v=zeros(nStrips,1);

 

for(j=1:nStrips)

    nPoints=j+1;

    X=linspace(from,to,nPoints);

    h=X(2)-X(1);

   

    f=zeros(length(X),1);

    for(i=1:length(X))

      x=X(i);

      f(i)=eval(func);

    end 

    sum=0;

    for(i=1:length(X))

        if(i==1 | i==length(X) ) 

            sum=sum+f(i);

        else

            sum=sum+2*f(i);   

        end

    end

    sum=sum/2;

    sum=sum*h;

    v(j)=sum;

end