Can someone check my for loop?

조회 수: 1 (최근 30일)
Bri
Bri 2014년 10월 9일
댓글: Star Strider 2014년 10월 10일
I have to create a function m file called mylength(f,a,b,n) which takes four inputs:
f: A function handle.
a: A real number.
b: A real number.
n: A positive integer.
Note: You may assume that f(x) is differentiable on [a, b] and that a < b.
Does: Calculates the length of f(x) on [a, b] using the formula L = the integral from a to b of the square root of (1 + f′(x)^2 dx) but with the integral approximated using a for loop to calculate a left sum with [a, b] divided into n subintervals.
Returns: This approximated length.
Here is sample data and correct answers to the sample data.
a = mylength(@(x) x^2,0,2,5)
a = 4.0480127986983730101003658887008
a = mylength(@(x) sin(x),pi,2*pi,10)
a = 3.820197787492867218055528594355
Here is my code.
function l=mylength(f,a,b,n);
syms x;
r=(b-a)/n;
L = sqrt(1+diff(f(x))^2);
l=0;
for q=(a:n-1);
y=subs(f(x),q);
area=r*y;
l=vpa(l+subs(L,r*area));
end
end
It does not return the same answers as the sample data, and I was pretty sure my code was right. Can you please let me know what is wrong with it?
Thanks
  댓글 수: 2
Geoff Hayes
Geoff Hayes 2014년 10월 10일
Bri - what are the answers that you are getting?
Bri
Bri 2014년 10월 10일
For the first sample data I am getting:
a =10.120031996745932525250914721752
and for the second sample data I am getting:
a =12.160067229364235067628002381161

댓글을 달려면 로그인하십시오.

채택된 답변

Star Strider
Star Strider 2014년 10월 10일
This hits ‘sin(x)’ spot on but slightly underestimates ‘x^2’:
syms x;
r=(b-a)/(n-1);
s = a:r:b;
L = sqrt(1+diff(f(x))^2);
l=0;
for q=1:n-1;
l=l+vpa(subs(L,s(q))*r);
end
  댓글 수: 4
Bri
Bri 2014년 10월 10일
Thanks.
Star Strider
Star Strider 2014년 10월 10일
My pleasure!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Calculus에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by