MATLAB : Simpson's 1/3 Rule

3.5k Views Asked by At

I've created a code for the Simpson's rule but I think I got the function wrong. I have no other sources to refer to (or they're too difficult to be understood). Here is my code:

function s = simpson(f_str, a, b, h)

f = inline(f_str);

n = (b-a)/h; 


x = a + [1:n-1]*h;
xi = a + [1:n]*h;


s = h/3 * (f(a) + f(b) + 2*sum(f(x)) + 4*sum(f(xi)));

end

Can anybody help see where is the wrong part?

1

There are 1 best solutions below

0
On

Assuming that the h in your function is the step size:

function s = simpson(f_str, a, b, h)
    % The sample vector will be
    xi = a:h:b;

    f = inline(f_str);

    % the function at the endpoints
    fa = f(xi(1));
    fb = f(xi(end));

    % the even terms.. i.e. f(x2), f(x4), ...
    feven = f(xi(3:2:end-2));

    % similarly the odd terms.. i.e. f(x1), f(x3), ...
    fodd = f(xi(2:2:end));

    % Bringing everything together
    s = h / 3 * (fa + 2 * sum(feven) + 4 * sum(fodd) + fb);
end

Source:
https://en.wikipedia.org/wiki/Simpson%27s_rule