finding area under curve by using nth number of trapezoid

Hi so i have to find the inegral of a function f over a given interval with a user specified number of trapezoids n
this is the function that i have come up with
function Q = trapz( a,b,n )
h = (b-a)/n;
x = a: h: b;
Q = 0;
for i= 0:1:n
Q = Q + 2*func (x(i));
end
Q = Q+f(x(1));
Q = Q + f((x(n+1)));
Q = Q* h/2;
end
I also defin func (x(i)) as
function value = func(xi)
value = sin (xi);
end
however when i run the code it said array indices must be positive integer or logical value, What does this mean, and how can i fix it? thank you

Answers (1)

You can pass a function into a function.
f=@(x)sin(x);
function A = trapz(a,b,n,f)
x=linspace(a,b,n+1);
h=(b-a)/n;
A=0;
for i=1:n
A=A+.5*(f(x(i))+f(x(i+1)))*h;
end
end

Categories

Find more on Mathematics in Help Center and File Exchange

Products

Tags

Asked:

on 26 Oct 2019

Answered:

on 26 Oct 2019

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!