[Math] Solving a system with Newton’s method in matlab

MATLABnumerical methods

I have the following non-linear system to solve with Newton's method in matlab:

x²+y²=2.12
y²-x²y=0.04

What is the linear equation system to be solved? Should I calculate the Jacobian matrix? I should use the starting variables x=1, y=1 and solve it with a matlab program with an error less than 10^-6. .Can you tell me how to do it?

Update

Here is my solution that is the same as matlab's solver. It's just like Newton for scalar and in vector form:

>>f=inline('x(1)^2+x(2)^2-2.12; x(2)^2-x(1)^2*x(2)-0.04]');
>>x=fsolve(f,x)
equation solved
x=
1.006852730995833
1.051783055209322
>>while dxnorm>0.4e-6 & iter<10
f=[x(1)^2+x(2)^2-2.12;x(1)^1-x(1)^2*x(2)-0.4];
J=[2*x(1) 2*x(2);-2*x(1)*x(2) 2*x(2)*x(1)^2];
dx=-J\f
x=x+dx
dxnorm=norm(dx,inf), iter=iter+1;
end
>>x, iter
x=1.006852730995833
1.051783055209322

Best Answer

Unfortunately, your update doesn't convince me you did the correct job, based on your script, your x variable is already the answer and residing in the workspace, the second time when your own scripts are being executed, only one iteration has been made, not the whole Newton's method.

If you are allowed to use Symbolic Toolbox to compute the Jacobian, there is a more universal way of doing instead of just carrying out a problem-oriented script. Here is a modified version to match your notation of an old implementation of mine for Newton's method, and this could be easily vectorized for a multi-dimensional nonlinear equation system using varargin input, and do a string size check on the inline function you passed to the following function.

function [s J] = newton(f,p0,tol,MaxIter)
format long
x = sym('x'); y = sym('y'); 
F = f([x,y]);
% Compute the Jacobian matrix symbolically
J = jacobian(F);
invJ = inv(J);
s = zeros(MaxIter,2);
s(1,:) = p0;
dsnorm = inf;
iter = 1;

while dsnorm>tol && iter<MaxIter
    ds = -subs(invJ,[x y],s(iter,:))*f(s(iter,:));
    s(iter+1,:) = s(iter,:) + ds';
    dsnorm = norm(ds,inf);
    iter = iter+1;
end
s = s(1:iter,:);

end

This function accepts input f as an inline function, p0 is the initial guess, tol is the tolerance and MaxIter is the maximum iteration allowed, if the vectorized version of your input is:

  >>f=inline('[p(:,1).^2+p(:,2).^2-2.12; ...
   p(:,2).^2-p(:,1).^2.*p(:,2)-0.04]','p');

Then

>>s = newton(f,[1 1],0.4e-6,10)

would return:

s =
   1.000000000000000   1.000000000000000
   1.006666666666667   1.053333333333333
   1.006852189012140   1.051784722315402
   1.006852720492674   1.051783057117558
   1.006852720493521   1.051783057115295

As you can see the last output is different from yours, because basically what you had was fsolve output, however fsolve use trust-region-dogleg algorithm by default, not Newton's method, if your output coincides with fsolve's result, then your implementation should have a problem.