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);
step = step + 1;
exitEarly = true;
for k=1:length(x)
if abs(x(k)-y(k))>tol
exitEarly=false;
end
end
if exitEarly
break;
end
x = y;
end
end
Try the above and see what happens!
Best Answer