Can someone check my for loop?
조회 수: 1 (최근 30일)
이전 댓글 표시
I am suppose 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.
This is my code:
function l=mylength(f,a,b,n);
syms x;
for w=(a:(b-a)/n:b);
y=subs(f(x),w);
l=vpa(int(sqrt(1+(diff(f(x)))^2),a,w));
a=w;
end
end
Here is sample data provided by my professor along with the correct answer 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
My code is not getting these answers. I am getting a =1.4947291280552747936216400307868, and a =
0.44067936609310253784512035349948 respectively. Can someone tell me why my code is not producing the correct answers? Where is my code wrong? I think it has something to do with calculating the left sum, I don't think my code is written correctly to calculate the left sum.
댓글 수: 0
채택된 답변
Star Strider
2014년 10월 7일
You need to sum ‘l’ (lower case ‘L’). Then it works.
Doing that, I got your professor’s answer for ‘sin(x)’ but not for ‘x^2’. I suspect that with your same code giving the correct answer for one and the incorrect answer for the other, one of your professor’s answers is incorrect.
댓글 수: 4
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!