Using Trapz in matlab

10 次查看(过去 30 天)
Brandon
Brandon 2013-3-5
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

采纳的回答

Youssef  Khmou
Youssef Khmou 2013-3-5
编辑:Youssef Khmou 2013-3-5
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 个评论
Brandon
Brandon 2013-3-5
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 2013-3-5
编辑:Youssef Khmou 2013-3-5
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 .

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Numerical Integration and Differentiation 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by