Matlab中的Newton Raphsons方法?

jon*_*jon 1 matlab newtons-method

Newtons-Raphsons方法很容易在Mathematica中实现,但在Matlab中似乎有点困难.如果我可以将函数传递给函数以及如何将派生函数用作函数,我不会得到.

newtonRaphson[f_, n_, guess_] := 
 If[n == 0, guess, newtonRaphson[f, n - 1, guess - f[guess]/f'[guess]]]
newtonRaphsonOptimize[f_, n_, guess_] := 
 If[n == 0, guess, 
  newtonRaphsonOptimize[f, n - 1, guess - f'[guess]/f''[guess]]]
Run Code Online (Sandbox Code Playgroud)

似乎你既不能导出函数句柄也不能导出文件中定义的函数,但我可能错了.

Ego*_*gon 6

你可以使用这样的实现:

function x = newton(f,dfdx,x0,tolerance)
err = Inf;
x = x0;
while abs(err) > tolerance
   xPrev = x;
   x = xPrev - f(xPrev)./dfdx(xPrev);
   % stop criterion: (f(x) - 0) < tolerance
   err = f(x); % 
   % stop criterion: change of x < tolerance
   % err = x - xPrev;
end
Run Code Online (Sandbox Code Playgroud)

并传递函数及其派生的函数句柄.这种衍生物可以通过一些不同的方法获得:手工分化,象征性区分或自动区分.您也可以在数字上执行区分,但这很慢并且需要您使用修改后的实现.所以我假设你已经以任何合适的方式计算了导数.然后你可以调用代码:

f = @(x)((x-4).^2-4);
dfdx = @(x)(2.*(x-4));
x0 = 1;
xRoot = newton(@f,@dfdx,x0,1e-10);
Run Code Online (Sandbox Code Playgroud)