Clear Filters
Clear Filters

Using Trapz in matlab

11 views (last 30 days)
Brandon
Brandon on 5 Mar 2013
Estimate the following integral using the trapz matlab function and b) the matlab function quad. Use n=2,4,8,16,32,64,128 and plot the difference bewtween the two methods as a function of n.
The function is as follows. sqrt(x)./(x+2)dx 1<=x<=3
So i am able to comfortable get the quad. However I can't seem to get a value for trapz. Here is what I have tried
First I made a for loop, Since I know that trapz operates on data not functions.
for k=1:7 y=2.^k end
However I'm not sure how to implement the for loop into solving the integral.
also how would I plot the difference bewtween the two methods as a function of n. I don't even understand what that means.
Thanks for the help

Accepted Answer

Youssef  Khmou
Youssef Khmou on 5 Mar 2013
Edited: Youssef Khmou on 5 Mar 2013
hi, Brandon
In this example you have to use function handle ,so what i understand is that you need to see when the two methods are equal. Here is a proposition :
1) You create a function handle :
f=@(x) sqrt(x)./(x+2);
2) You create the the number of spacing elements on which Trapz method wil be evaluated :
n=2.^(1:7); %
3) You initialize the vectors that will contain the numercial intergations :
I1=zeros(1,7);
I2=zeros(1,7);
4) You implement a loop : ! YOU have to complete the two lines
for ii=1:length(n)
x=linspace(1,3,n(ii));
I1(ii)=quad(f,...... % INCOMPLETE LINE
I2(ii)=trapz(x,..... % INCOMPLETE LINE
end
Now you can see when the two methods are equal .
figure, plot(n,I1); hold on, plot(n,I2,'r'),legend('QUAD','TRAPZ')
  2 Comments
Brandon
Brandon on 5 Mar 2013
Hi I appreciate the response and explanation. However the only thing you failed to answer was my question on how to use trapz properly. I'm really struggling with that.
Thanks!
Youssef  Khmou
Youssef Khmou on 5 Mar 2013
Edited: Youssef Khmou on 5 Mar 2013
ok fine: " I2(ii)=trapz(x,f(x));" if you use "trapz(f(x))" the Integral is evaluated with default spacing : one, but with the first formula " trapz(x,f(x))" you impose on the function to eval the Integral on the specified x Axis , and our x Axis increases in sampling in the loop and then convereges to QUAD .

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!