1

Matlab で Newton アルゴリズムの実装を作成しようとしています。

式を使用して関数を呼び出すと:

result = NewtonMethod(x(1).^2 - 2.1*x(1).^4 + (x(1).^6)/3 + x(1)*x(2) - 4*x(2).^2 + 4*x(2).^4, [0 0], 0.1, 10)

次のエラー メッセージが表示されます。

??? Undefined function or method 'hessian' for input arguments of type 'double'.

Error in ==> NewtonMethod at 13
    H = hessian(f, x0);

何が悪いのかわかりません。たぶん、Matlabに詳しい人が私を助けてくれるでしょう。

以下は私のコードです:

function xnext = NewtonMethod(f, x0, eps, maxSteps)

% x0        -   starting point (2 – dimensional  vector)
% H         -   matrix of second derivatives (Hessian)
% eps       -   required  tolerance of calculations
% maxSteps  -   length of step

x = x0;

for n=1:maxSteps

    % determine the hessian H at the starting point x0,
    H = hessian(f, x0);

    % determine the gradient of the goal function gradf at the point x,
    gradF = gradient(f, x);

    % determine next point
    xnext = x - inv(H) * x * gradF;

    if abs(xnext - x) < eps
        return                  %found
    else
        x = xnext;              %update
    end
end

Matlab との最初の接触です。

アップデート:

今、私はエラーを持っています:

??? Error using ==> mupadmex
Error in MuPAD command: Index exceeds matrix dimensions.

Error in ==> sym.sym>sym.subsref at 1381
            B = mupadmex('symobj::subsref',A.s,inds{:});

私が入力した:

syms x
result = NewtonMethod(x(1).^2 - 2.1*x(1).^4 + (x(1).^6)/3 + x(1)*x(2) - 4*x(2).^2 + 4*x(2).^4, [0 0], 0.1, 10)
4

1 に答える 1

3
x(1).^2 - 2.1*x(1).^4 + (x(1).^6)/3 + x(1)*x(2) - 4*x(2).^2 + 4*x(2).^4

NewtonMethod関数が呼び出される前に double に縮小されるため、コードが に達するhessian(f, x0)と、2 つの double 引数が渡されますが、これはサポートされている構文ではありません

シンボリック関数の適切な指定に関する注意事項を確認し、それを に渡しますNewtonMethod


数値最適化を行ってから長い時間が経ちましたが、次を見てください。

function xn = NewtonMethod(f, x0, eps, maxSteps)

% x0        -   starting point (2 – dimensional  vector)
% H         -   matrix of second derivatives (Hessian)
% eps       -   required  tolerance of calculations
% maxSteps  -   length of step

syms x y

H = hessian(f);
gradF = gradient(f);

xi = x0;

for i=1:maxSteps

    % evaluate f at xi
    zi = subs(f, [x,y], xi);

    % determine the hessian H at the starting point x0,
    hi = subs(H, [x,y], xi);

    % determine the gradient of the goal function gradf at the point x,
    gi = subs(gradF, [x,y], xi);

    % determine next point
    ss = 0.5;  % step size
    xn = xi - ss.* (inv(hi) * gi);

    % evaluate f at xn
    zn = subs(f, [x,y], xn);

    % some debugging spam
    zd = zn - zi;                          % the change in the value of the
    si = sprintf('[%6.3f, %6.3f]', xi);    %   function from xi -> xn
    sn = sprintf('[%6.3f, %6.3f]', xn);
    printf('Step %3d: %s=%9.4f -> %s=%9.4f  :  zd=%9.4f\n', i, si, zi, sn, zn, zd);

    % stopping condition
    if abs(xi - xn) < eps
        return               %found
    else
        xi = xn;             %update
    end
end

そしてと呼ばれる

result = NewtonMethod(f, [0; 1], 0.001, 100)
于 2014-05-13T16:48:04.803 に答える