Using Trapz in matlab

조회 수: 4 (최근 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