Can someone check my for loop?

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.

 Respuesta aceptada

Star Strider
Star Strider el 7 de Oct. de 2014

0 votos

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 comentarios

Bri
Bri el 7 de Oct. de 2014
I'm sorry, I don't understand what you mean by sum 'l'. Can you please explain?
Yes.
Summing ‘l’ in your loop involves two changes:
syms x;
w=a:(b-a)/(n-1):b;
l = 0;
for k1 = 1:length(w)
y=subs(f(x),w(k1));
l = l + vpa(int(sqrt(1+diff(f(x))^2),a,w(k1)));
a=w(k1);
end
Initially set ‘l’ to zero and then add to it in each iteration of the loop. It has the correct answer at the end of the loop.
Bri
Bri el 7 de Oct. de 2014
Thanks
Star Strider
Star Strider el 7 de Oct. de 2014
My pleasure!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

Bri
el 7 de Oct. de 2014

Comentada:

el 7 de Oct. de 2014

Community Treasure Hunt

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

Start Hunting!

Translated by