Answer this Newtons Method problem

3 次查看(过去 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 CenterFile Exchange 中查找有关 Get 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