2 views (last 30 days)
Dave Regan on 2 Dec 2014
Edited: Dave Regan on 2 Dec 2014
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

Andrew Reibold on 2 Dec 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 CommentsShow 1 older commentHide 1 older comment
Dave Regan on 2 Dec 2014
Edited: Dave Regan on 2 Dec 2014
I want the x value to overwrite the previous one... I'm trying to write a program for newtons method. I want the loop to terminate or break once x equals the same as the previous x up to 8 decimals.
I tried to figure out a way to use 'if' 'then' 'and' statements to get it to work and had no luck either. I also tried to add count to count the iterations and apply the break if count>2 and x(i-1)==x(i) but it said i have too many or too few inputs for &.
I deleted my other "answer" so not to confuse anyone.