MATLAB Composite Trapez-ium Rule Approximation of Integral f(x)dx

AI Thread Summary
The discussion focuses on creating a MATLAB function to approximate the integral of a given function using the Composite Trapezium Rule. The user presents an initial implementation but is unsure about the correct definition and usage of the function f within the algorithm. Questions arise regarding the application of the function in another m-file using the feval command, particularly in relation to defining the function f properly. Clarifications are sought on how to correctly use feval to evaluate the function within the context of the CTR function. The conversation emphasizes the need for precise function definitions and proper command usage in MATLAB for successful implementation.
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.
 

Similar threads

Replies
2
Views
3K
Replies
3
Views
1K
Replies
1
Views
4K
Replies
1
Views
9K
Replies
3
Views
17K
Replies
1
Views
1K
Back
Top