Trying to make loop that stops when xnew is closer to xlast by .001
1 次查看(过去 30 天)
显示 更早的评论
I'm trying to make a code that loops until it stops when one equation (Xnew) gets close enough to the second equation (Xlast) that it's .001 away. By inputting the r0=3, r1=1, r2=3.6, r3=2.1, theta0=pi, theta1=pi/4, theta2=0, theta3=1.25 it gets the correct Xnew of -0.9318 and 2.2382, but then when it starts the loop, the loop stops too early. Can anyone help?
function [ theta2, theta3 ] = kenimaticprob( r0, r1, r2, r3, theta0, theta1 ) %UNTITLED2 Summary of this function goes here % Detailed explanation goes here r0=input('enter the length of fixed link: ') r1=input('enter the length of the link: ') r2=input('enter the length of coupler link: ') r3=input('enter the length of driven crank link: ') theta0=input('enter the value of the angle between the fixed link and the horizontal: ') theta1=input('enter the value of the angle between the crank link and the fixed link: ') theta2=input('guess the angle theta2: ') theta3=input('guess the angle theta3: ') f1=r2*cos(theta2)+r3*cos(theta3)+r0*cos(theta0)+r1*cos(theta1); f2=r2*sin(theta2)+r3*sin(theta3)+r0*sin(theta0)+r1*sin(theta1); f=[f1; f2] g=[-r2*sin(theta2), -r3*sin(theta3) ; r2*cos(theta2), r3*cos(theta3)] Xnew=[theta2; theta3]-inv(g)*f Xlast=[1; 3] loop=1 Xnew=Xlast-inv(g)*f; Xlast=Xnew;
while(1)
loop=loop+1 Xnew=Xlast-inv(g)*f; if Xlast~Xnew < 0.001 % Some tolerance. break; end
end
0 个评论
回答(1 个)
Matt Kindig
2013-4-17
编辑:Matt Kindig
2013-4-17
If you could format your code using the 'Code' button above, that would help us read it. That said, I think the problem is in your line:
if Xlast~Xnew < 0.001
The ~ is not an operator. I think you want to do something like this:
if abs(Xlast-Xnew) < 0.001 %note the use of abs() to avoid sign issues
Even better, you can make this your condition in your while loop, instead of the while(1) condition. Like this:
while abs(Xlast-Xnew) >= 0.001
which does the same thing.
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!