why is my for loop not working?

19 views (last 30 days)
KIPROTICH KOSGEY
KIPROTICH KOSGEY on 13 Feb 2026 at 10:16
Moved: Image Analyst on 13 Feb 2026 at 15:51
y=@(x) x^2-4;
x1=input('Enter the value of x1:');
x2=input('Enter the value of x2:');
x3=input('Enter the value of x3:');
for i=1:100
L1=(x2-x3)/(x3-x1);
xf=x3+L1*(x3-x1);
y1=abs(y(x1));
y2= abs(y(x2));
y3=abs(y(x3));
yf=abs(y(xf));
ynext=sort([y1 y2 y3 yf]);
if y1==max(ynext)
x1=xf;
elseif y2==max(ynext)
x2=xf;
else
x3=xf;
end
if y(xf)<10^-10
break
end
end
fprintf('the root: %f\n the number of iterations: %d\n',xf,i)

Answers (1)

dpb
dpb about 2 hours ago
Moved: Image Analyst about 1 hour ago
Probably because you're testing floating point values for exact equality -- see isapprox and ismembertol
See the <example in eq for more> for what is likely the cause.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!