break loop when answer is same as last answer

4 views (last 30 days)
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

Answers (1)

Andrew Reibold
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 Comments
Andrew Reibold
Andrew Reibold on 2 Dec 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?
Dave Regan
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.

Sign in to comment.

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!