How do I vectorize Rombergs Method for better speed

42 Views Asked by At

Hello I have written the following Romberg's Method and I would like to ask you how can i vectorize it for faster performance?

Here is what i wrote:

function [r,out] = romberg1(f,a,b,n)
h = (b - a) ./ (2.^(0:n-1));
r(1,1) = (b - a) * (f(a) + f(b)) / 2;
for j = 2:n
    subtotal = 0;
    for i = 1:2^(j-2)
        subtotal = subtotal + f(a + (2 * i - 1) * h(j));
    end
    r(j,1) = r(j-1,1) / 2 + h(j) * subtotal;
    for k = 2:j
        r(j,k) = (4^(k-1) * r(j,k-1) - r(j-1,k-1)) / (4^(k-1) - 1);
    end
end
out=r(n,n);
1

There are 1 best solutions below

0
On

The following is a vectorized version of your code. It assumes that the function $f$ has been vectorized.

function [r,out] = romberg1_vec(f,a,b,n)
h = (b - a) ./ (2.^(0:n-1));
r(1,1) = (b - a) * (f(a) + f(b)) / 2;
N = 1;
for j = 2:n
    subtotal = sum(f(a + (2 * (1:N) - 1) * h(j)));
    r(j,1) = r(j-1,1) / 2 + h(j) * subtotal;
    for k = 2:j
        r(j,k) = (4^(k-1) * r(j,k-1) - r(j-1,k-1)) / (4^(k-1) - 1);
    end
    N = 2 * N;
end
out=r(n,n);
end