break loop when answer is same as last answer
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (1)
Andrew Reibold
le 2 Déc 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 commentaires
Andrew Reibold
le 2 Déc 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?
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!