How to make a loop until a function has a nonzero limit?

1 次查看(过去 30 天)
I'm making an application for L'hopitals rule so the condition has to be until one of the functions has derived enough to have a nonzero limit. For this application, I have to use a while loop so here's what I got already.
while (limit(f,x,0)==0 limit(g,x,0)==0)
a=diff(f(x));
b=diff(g(x));
end;
y=(limit(f,x,0))/(limit(g,x,0))
My problem is since I need to assign variables to differentiate the two functions and the variables cannot be the same as the ones I assigned to the functions, how can I tell the while loop to continue to derive the functions when the derived functions has a different variable?

回答(2 个)

Matt J
Matt J 2012-10-14
If you're just trying to avoid overwriting f and g, why not just make prior copies of them:
a=f;
b=g;
while (limit(a,x,0)==0 limit(b,x,0)==0)
a=diff(a(x));
b=diff(b(x));
end;
y=(limit(a,x,0))/(limit(b,x,0))

Star Strider
Star Strider 2012-10-14
编辑:Star Strider 2012-10-14
I am not certain I completely understand your problem, but if you want to continue to differentiate your functions until you get a finite result, I suggest this approach:
syms a b c d f g x
f(x) = sin(x)
g(x) = 1 - exp(x)
c = f(x)
d = g(x)
k1 = 1;
while (limit(c,x,0)==0) && (limit(d,x,0)==0)
a=diff(c(k1,:));
b=diff(d(k1,:));
k1 = k1 + 1
c(k1,:) = a
d(k1,:) = b
end;
y = (limit(c(k1,:),x,0))/(limit(d(k1,:),x,0))
Vectors c and d store the intermediate results, so you do not overwrite your original functions.
  2 个评论
Andy
Andy 2012-10-14
I forgot to mention but the f and g in this function are function handles
Star Strider
Star Strider 2012-10-14
编辑:Star Strider 2012-10-14
I could only get this to work in the Symbolic Math Toolbox. I assumed that when you referred to limit in your code snippet, you were using it.
I just now tried the code I posted with f and g redefined as:
f = @(x) sin(x)
g = @(x) cos(x) - exp(x)
and it worked just as well as with the original function definitions.
NOTE: I'm using 2012b.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by