why is this code not working?
Show older comments
I'm using this code that is supposed to work as is, but I instead get errors as I try to input things, normally "variable not defined" and "array indices must be positive integers or logical values". It is a function that does the Newton Raphson approximation of a function given its derivative and more parameters. Any help appreciated.
function [root,iter,v] = newton(f,df,x0,itmax,eps)
% this program computes the approximated root given by Newton method
% for f(x)=0
% input:
% f,df: function f(x) and derivative of f(x)
% x0: initial guess
% itmax: maximum number of iterations allowed
% eps: error tolerance (we stop when |xnew-xold|<eps*max(1,|xold|)
% output:
% root: xnew (when convergence is achieved)
% iter: number of given iterations
% v: a matrix that writes on each iteration [xold f df xnew-xold]
iter=0;
coc=1.e9;
x=x0;
while abs(coc)>eps*max(1,abs(x)) && iter<=itmax
iter=iter+1;fx=f(x);dfx=df(x);
coc=fx/dfx;
v(iter,1:4)=[x fx dfx coc];
x=x-coc;
end
if iter>itmax
'Newton-Raphson iteration does not converge'
return
end
root=x;
end
1 Comment
Torsten
on 7 Nov 2022
Please show us how you call the function.
Accepted Answer
More Answers (0)
Categories
Find more on Newton-Raphson Method 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!