why is this code not working?

조회 수: 2 (최근 30일)
Oskyrim
Oskyrim 2022년 11월 7일
편집: Torsten 2022년 11월 7일
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
Torsten
Torsten 2022년 11월 7일
Please show us how you call the function.

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

채택된 답변

David Hill
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)
root = 3.6314
iter = 5
v = 5×4
3.0000 7.2401 -6.6499 -1.0888 4.0888 -8.1831 -19.1364 0.4276 3.6611 -0.4767 -16.2202 0.0294 3.6317 -0.0049 -15.8834 0.0003 3.6314 -0.0000 -15.8798 0.0000
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개)

카테고리

Help CenterFile Exchange에서 Newton-Raphson Method에 대해 자세히 알아보기

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by