MATLAB: Newton’s Method for nonlinear system vector operation.

MATLABnewton's method

when i was doing newton's method for nonlinear system, when I entered following code it tells me that it could not do subtraction between two vectors with different dimension. The thing is F is a 2×1 vector, and J is jacobian matrix of F which is 2×2. so I dont know what is going on with my code. the following is the code.
a = newton(@F, @J, [1,1])
=========================================
function y = newton(f,j,x)
step = 1;
finalstep = 10;
y = zeros (2,1);
while step < finalstep
d = j(x)\(-f(x));
y = x + d;
disp(y);
x = y;
end
end
==========================================
function f = F(x)
x1 = x(1);
x2 = x(2);
f = zeros(2,1);
f(1) = x1^2-x2^2+2*x2; % f1(x1,x2)
f(2) = 2*x1+x2^2-6; % f2(x1,x2);
end
==========================================
function j = J(x)
x1 = x(1);
x2 = x(2);
j = zeros(2,2);
j(1,1) = 2*x1; % df1x1
j(1,2) = -2*x2+2; % df1x2
j(2,1) = 2; % df2x1
j(2,2) = 2*x2; % df2x2;
end

Best Answer

Lechen - if I run through your code, I observe the following error
Error using +
Matrix dimensions must agree.
Error in newton.m
y = x + d;
because x is a 1x2 matrix and d is a 2x1 matrix. The simplest fix for this is to just change the input x from a 1x2 matrix to one that is 2x1
a = newton(@F, @J, [1;1])
That will fix the error message. Now look closer at the newton function
function y = newton(f,j,x)
step = 1;
finalstep = 10;
y = zeros (2,1);
while step < finalstep
d = j(x)\(-f(x));
y = x + d;
disp(y);
x = y;
end
end
Note how the code does not increment the step local variable, so the code will become stuck in an infinite loop. Add a line to increment this variable. Also, consider adding it a line of code that compares x and y - if the difference between the two vectors (for each element) is less than some tolerance, then assume that no better solution will be found and so break out of the loop. The above then becomes something like
function y = newton(f,j,x)
step = 1;
finalstep = 10;
y = zeros (2,1);
tol = 1e-5;
while step < finalstep
d = j(x)\(-f(x));
y = x + d;
disp(y);
% increment step
step = step + 1;
% compare each element of x and y
exitEarly = true;
for k=1:length(x)
if abs(x(k)-y(k))>tol
% pair k exceeds tolerance so do not exit
% early
exitEarly=false;
end
end
if exitEarly
break;
end
x = y;
end
end
Try the above and see what happens!