I'm trying to run a loop until a condition is met
2 次查看(过去 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!