Using Trapz in matlab
10 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
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 个评论
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 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!