why is my for loop not working?

27 views (last 30 days)
KIPROTICH KOSGEY
KIPROTICH KOSGEY on 13 Feb 2026 at 10:16
Edited: Torsten about 13 hours ago
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)
  2 Comments
KIPROTICH KOSGEY
KIPROTICH KOSGEY 11 minutes ago
Anyone out there to shed some light on the above?
Torsten
Torsten 43 minutes ago
Edited: Torsten 43 minutes ago
Should your code be an implementation of the secant method to get a root of y ? Or what is its purpose ?

Sign in to comment.

Answers (1)

dpb
dpb on 13 Feb 2026 at 14:38
Moved: Image Analyst on 13 Feb 2026 at 15:51
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!