break loop when answer is same as last answer
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Im trying to break this loop when x(i)==x(i-1), but i get...
Attempted to access x(0); index must be a positive integer or logical.
Error in test (line 13)
if x(i-1)==x(i)
Here is the code...
function []=test
syms x
digits(9);
func= input('Please enter f(x) = ');
Xest= input('Pleae enter an initial guess = ');
d=diff(func,x);
x=Xest;
for i = 0:15
ds=eval(d);
fs=eval(func);
x = x-((fs)./(ds));
vpa(x)
if x(i-1)==x(i)
break
end
end
end
0 comentarios
Respuestas (1)
Andrew Reibold
el 2 de Dic. de 2014
The reason it is failing - Matlab does NOT accept ZERO indices. The very first value of x is x(1), not x(0). Your script calls for x(0)!
Why does i go from 0 to 15 instead of 1 to 15? And even then, you will have x(i-1) which is still 0! You will have to rethink through how you do this to avoid x(0)
2 comentarios
Andrew Reibold
el 2 de Dic. de 2014
Uh oh, if you add your comments/replies as additional 'answers' other people may think you are already being helped and might not try to give their input. Make sure to try to avoid this in the future;
Anyway, I was looking at your code again and here is the issue... You are looping through to try to call different indices of x. x(1), x(2), x(3)... and so on. But you never set x(1), x(2), x(3)
You just set this
x = x-((fs)./(ds))
You only have one x value. The next time it runs the loop, it just overwrites the old one.
I'm not sure what you are trying to loop through or why you have 15. Can you elaborate?
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!