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!
