I'm trying to run a loop until a condition is met
조회 수: 1 (최근 30일)
이전 댓글 표시
I want to run a for loop until my slope of a line is equal to another number:
I have a secant line between two points and I'm calculating every tangent line starting from one point to another.
I can't seem to end the loop when the tangent line slope equals the secant line
clear all
a=-2;
b=8;
x=linspace(-10,10,100);
y=x.^3;
yb=b.^2;
ya=a.^2;
msecant=(yb-ya)/(b-a);
secant=msecant*(x-a)+ya;
for i=1:100
mt=3*x(i)^2;
inter =1;
if abs(mt-msecant)>.4
yt=mt*(x-x(i))+y(i);
else
return
end
end
댓글 수: 2
답변 (2개)
John D'Errico
2022년 10월 25일
편집: John D'Errico
2022년 10월 25일
Simple rule #1: A for loop is best when you KNOW how many iterations you wish to perform. How many times do you want it to loop? If you know the answer in advance, then use a for loop.
Simple rule #2: Use a while loop when you don't know how many iterations you will perform. It has a test in there, to allow the loop to gracefully terminate.
In some cases, you may decide that you want to perform N iterations, BUT if some condition is met, then you are willing to terminate early. Then you might decide to choose between the two programming styles. Either could be appropriate.
The last point is that every rule has an exception. You can use the break statement to exit a for loop when something special happens. But you can just as easily set it up with a while loop, incrementing a counter, and then terminate if either the counter exceeds N, OR if the termination condition is met. Your choice.
댓글 수: 0
Image Analyst
2022년 10월 25일
They never get within 0.4 of each other. I suggest you alter your ending condition. See this
clear all
a=-2;
b=8;
x=linspace(-10,10,100);
y=x.^3;
yb=b.^2;
ya=a.^2;
msecant=(yb-ya)/(b-a);
secant=msecant*(x-a)+ya;
for i=1:100
fprintf('i = %d', i)
mt=3*x(i)^2;
inter =1;
fprintf(' mt = %.2f. msecant = %.2f\n', mt, msecant)
if abs(mt-msecant)>.4
yt=mt*(x-x(i))+y(i);
else
return
end
end
댓글 수: 2
Image Analyst
2022년 10월 26일
Make x have more elements, like a million or so. Of course in that case, don't use fprintf() or it will take forever.
참고 항목
카테고리
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!