romberg’s method in matlab

To implement Romberg’s method in MATLAB, follow these steps:

  1. Define a function to be integrated, let’s call it fun.
  2. Define the limits of the integration, a and b.
  3. Specify the number of rows n in the Romberg’s table you want to compute.
  4. Initialize the Romberg’s table R with zeros of size n by n.
  5. Compute the first column of R, which contains the trapezoidal rule estimates of the integral with step sizes h, h/2, h/4, …, h/2^(n-1).
  6. Compute the remaining columns of R recursively using the formula R(i,j) = (4^(j-1) * R(i,j-1) - R(i-1,j-1)) / (4^(j-1) - 1), for i = j+1, j+2, ..., n and j = 1, 2, ..., n-1.
  7. The last element R(n,n) of the table is the most accurate estimate of the integral.

Here’s the MATLAB code for Romberg’s method:

main.m
function I = romberg(fun, a, b, n)
% ROMBERG   Romberg's method for numerical integration.
% I = ROMBERG(FUN, A, B, N) estimates the integral of the function FUN
% from A to B using Romberg's method with N rows of the table.

h = (b-a)./(2.^(0:n-1));       % step sizes
R = zeros(n);                  % initialize table with zeros
R(1,1) = (b-a)*(fun(a)+fun(b))/2; % first trapezoidal approximation

for j = 2:n
    % composite trapezoidal rule approximations with step size h(j)
    R(j,1) = R(j-1,1)/2 + h(j)*sum(fun(a+h(j):2*h(j):b-h(j)));
    % Romberg recursive formula for higher order approximations
    for i = j:n
        R(i,j) = (4^(j-1)*R(i,j-1) - R(i-1,j-1))/(4^(j-1)-1);
    end
end

I = R(n,n);                    % most accurate estimate of integral

end
771 chars
22 lines

You can use this function as follows:

main.m
>> fun = @(x) exp(-x.^2);   % example function
>> romberg(fun, 0, 1, 5)    % integral from 0 to 1 with 5 rows of table
ans =
    0.7468
136 chars
5 lines

gistlibby LogSnag