Answer this Newtons Method problem

2 ビュー (過去 30 日間)
Yash Singhal
Yash Singhal 2021 年 8 月 13 日
回答済み: Wan Ji 2021 年 8 月 13 日
  1 件のコメント
James Tursa
James Tursa 2021 年 8 月 13 日
What have you done so far? What specific problems are you having with your code?

サインインしてコメントする。

回答 (1 件)

Wan Ji
Wan Ji 2021 年 8 月 13 日
why not use fsolve or fzero? The following is newton's method
function main
f = @(x) [
sin(x(1)*x(2)) + x(1) - x(2);
x(2)*cos(x(1)*x(2)) + 1;
];
TOL = 1e-3;
err = 1;
x0 = [1;2];
iter = 0;
fprintf('Iteration\tx1\tx2\tf1(x1,x2)\tf2(x1,x2)\n');
while err>TOL
iter = iter + 1;
x1 = x0 - diffmat(f,x0,1e-3)\f(x0) ;
err = norm(x1-x0);
x0 = x1;
fval = f(x1);
fprintf('%d\t%f\t%f\t%f\t%f\t\n', iter, x1(1), x1(2), fval(1), fval(2));
end
end
function m = diffmat(fun, x, h)
f0 = fun(x);
m = zeros(numel(f0), numel(x));
for i = 1:1:numel(x)
x0 = x;
x0(i) = x0(i) + h;
fi = (fun(x0) - f0)/h;
m(:,i) = fi;
end
end
Result printed:
Iteration x1 x2 f1(x1,x2) f2(x1,x2)
1 1.079754 1.945311 -0.002579 0.017148
2 1.086147 1.943707 -0.000034 0.000076
3 1.086187 1.943685 0.000000 -0.000000

カテゴリ

Help Center および File ExchangeGet Started with Optimization Toolbox についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by