Can someone check my for loop?

1 view (last 30 days)
Bri
Bri on 7 Oct 2014
Commented: Star Strider on 7 Oct 2014
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.

Accepted Answer

Star Strider
Star Strider on 7 Oct 2014
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 Comments

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!