Can someone check my for loop?

1 visualización (últimos 30 días)
Bri
Bri el 7 de Oct. de 2014
Comentada: Star Strider el 7 de Oct. de 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.

Respuesta aceptada

Star Strider
Star Strider el 7 de Oct. de 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 comentarios
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 Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by