Trying to make loop that stops when xnew is closer to xlast by .001

조회 수: 1 (최근 30일)
Mike
Mike 2013년 4월 17일
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

답변 (1개)

Matt Kindig
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.

카테고리

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