why is my for loop not working?
32 views (last 30 days)
Show older comments
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)
3 Comments
Jan
on 17 Feb 2026 at 20:30
Edited: Jan
on 17 Feb 2026 at 20:31
@KIPROTICH KOSGEY: It is hard to answer to "not working". Of course the shown code ist working and it performs exactly the instructions as defined by the code. The result differ from your expectations, but you did not mention, what you expect. What is the intention of the code?
Answers (1)
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
1 Comment
Walter Roberson
on 17 Feb 2026 at 21:21
The code stores values in y1, y2, y3, yf, and then puts those values into an array using []. The values stored in the array will be bit-for-bit exact of the original values y1, y2, y3, yf (provided those are all the same datatype, which is true.) sort() of such an array will output bit-for-bit exact values, just re-arranged (exception: if different NaN representations were originally used, then the sort() will typically replace the unusual NaNs with a standard NaN.) max() of the output of sort() will result in bit-for-bit exact values.
Comparing the original value y1 to the output of max() is well defined; two bit-for-bit exact values will be compared, and they will either match or not. There is the possibility that NaN is being compared to NaN, which will give a false output.
The sort() is an unnecessary step, though: the code could easily have used
ynext=[y1 y2 y3 yf];
However...
if y(xf)<10^-10
That should likely be
if abs(y(xf))<10^-10
which in turn could be
if yf<10^-10
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!