why is my for loop not working?

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 comentarios

KIPROTICH KOSGEY
KIPROTICH KOSGEY el 16 de Feb. de 2026
Anyone out there to shed some light on the above?
Torsten
Torsten el 16 de Feb. de 2026
Editada: Torsten el 16 de Feb. de 2026
Should your code be an implementation of the secant method to get a root of y ? Or what is its purpose ?
Jan
Jan el 17 de Feb. de 2026
Editada: Jan el 17 de Feb. de 2026
@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?

Iniciar sesión para comentar.

Respuestas (1)

dpb
dpb el 13 de Feb. de 2026
Movida: Image Analyst el 13 de Feb. de 2026

1 voto

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.

1 comentario

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

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 13 de Feb. de 2026

Comentada:

el 17 de Feb. de 2026

Community Treasure Hunt

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

Start Hunting!

Translated by