I'm trying to run a loop until a condition is met
2 views (last 30 days)
Show older comments
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 Comments
Answers (2)
John D'Errico
on 25 Oct 2022
Edited: John D'Errico
on 25 Oct 2022
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 Comments
Image Analyst
on 25 Oct 2022
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 Comments
Image Analyst
on 26 Oct 2022
Make x have more elements, like a million or so. Of course in that case, don't use fprintf() or it will take forever.
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!