Why do I get this error: A(I): index out of bounds; value 2 out of bound 1 (line 13)

124 ビュー (過去 30 日間)
Mohanad Arafae
Mohanad Arafae 2016 年 11 月 13 日
回答済み: Roger Stafford 2016 年 11 月 14 日
function root=newtonmethod(f,fprime,x0,maxiter,tol)
%input:
% f string that names the function f(x).
% fprime string that names the derivative f’(x).
% x0 the initial point
% tol is the termination tolerances
% maxiter the maximum number of iteration
x(1) = x0;
n = 2;
while abs(f(x(n))) > tol & n < maxiter
m = n+1;
x(m) = x(n) - f(x(n))/fprime(x(n));
if x(n) - f(x(n))/fprime(x(n)) < 0
root = x(n);
break;
end
end
root = x(n)

回答 (2 件)

Daniel kiracofe
Daniel kiracofe 2016 年 11 月 13 日
Because the very first time the while statement's condition is checked, n=2, and x is a vector that has 1 element. You are asking to evaluate the 2nd element of an array that has only 1 element. You probably want to start with n=1 instead of n=2.

Roger Stafford
Roger Stafford 2016 年 11 月 14 日
Besides the error that Daniel gives you, another error is that ’n’ never changes within your while-loop, so the (corrected) loop would never stop unless you just happened to start with the right value.

Community Treasure Hunt

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

Start Hunting!

Translated by