break loop when answer is same as last answer

조회 수: 1(최근 30일)
Dave Regan
Dave Regan 2014년 12월 2일
편집: Dave Regan 2014년 12월 2일
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

답변(1개)

Andrew Reibold
Andrew Reibold 2014년 12월 2일
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
Dave Regan
Dave Regan 2014년 12월 2일
편집: Dave Regan 2014년 12월 2일
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.

댓글을 달려면 로그인하십시오.

Community Treasure Hunt

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

Start Hunting!

Translated by