break loop when answer is same as last answer
조회 수: 1 (최근 30일)
이전 댓글 표시
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
답변 (1개)
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
Andrew Reibold
2014년 12월 2일
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?
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!