Composite trapezium rule MATLAB function for numerical integration

Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
2 replies · 7K views
sara_87
Messages
748
Reaction score
0

Homework Statement



Write an algorithm and Matlab function JN, which uses the Composite Trapez-
ium Rule (CTR) to compute an approximation of the integral f(x) dx for an arbitrary
function f of one variable. The inputs should be a, b and N (the number of
subintervals), and f (the name of a Matlab function of one variable). The
output should be the approximate integral value JNf, i.e. the result of the
Composite Trapezium Rule for f.


Homework Equations





The Attempt at a Solution



function JN=CTR(a,b,N)
h=(b-a)/N;
JN=0;
for i=1:N
ti=a+i*h;
ti1=a+(i-1)*h;
f=f(ti);
JN=JN+h/2*(f(ti1)+f(ti))
end

Most of it looks right but I'm sure i have done something wrong. is there something missing with defining f.
Thank you
 
Physics news on Phys.org
Did you define f(x) somewhere? What's the point of f=f(ti) if you end up calling the function again anyway? The idea looks ok, it's just that you don't have all the specifics for MATLAB to me.
 
Oh i think i get it now. no worries.
i have another question:
i have a function; like the one above, how do i apply it in another m file. i mean i want to apply this to the function f=3x+2 using feval command. this is what i did:
JN=feval(N,x);
y=3*x+2;
but if i type in the command: CTR(0,0.9,20); an error comes up.
How do we use the feval command?
Thank you.