why is this code not working?
조회 수: 2 (최근 30일)
이전 댓글 표시
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
채택된 답변
David Hill
2022년 11월 7일
편집: Torsten
2022년 11월 7일
Function works fine.
f=@(x)x.^2.*sin(x)-x.*cos(x)+3;%sample function
df=@(x)x.^2.*cos(x)+3*x.*sin(x)-cos(x);
[root,iter,v]=newton(f,df,3,10,1e-8)
x=0:.01:5;
plot(x,f(x))
function [root,iter,v] = newton(f,df,x0,itmax,eps)
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
댓글 수: 0
추가 답변 (0개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
