Write a function trap fabn that computes the trapezoidal rul
Write a function trap (f,a,b,n) that computes the trapezoidal rule approximation to f(x) dx, where h = (b - a)/n and xi = a + ih. Test your function on sin(x) + cos(x) for 0 x pi/3. For a greater challenge, write a function simp for Simpson\'s rule, This formula requires n to be even. You may choose to check the input for this
Solution
function integral = trap(a,b,n,f)
h = (b-a)/n;
x = [a+h:h:b-h];
integral = h/2*(2*sum(feval(f,x))+feval(f,a)+feval(f,b));
function y = f(t)
y = t.*log(t);
. Matlab code for the Simpson’s rule
function integral = simp(a,b,n,f)
h = (b-a)/n;
xi0 = feval(\'f\',a)+feval(\'f\',b);
xi1 = 0;
xi2 = 0;
for i = 1:n-1
x = a+i*h;
if mod(i,2) == 0
xi2 = xi2+feval(\'f\',x);
else
xi1 = xi1+feval(\'f\',x);
end
end
xi = h*(xi0+2*xi2+4*xi1)/3;
x
