Newtons method for system of nonlinear equations
20 views (last 30 days)
Show older comments
function p = sysNewton(f,J,x0,tol)
% f is the system of equations as a column vector
% this an anonymous function with a vector input and vector output
% J is the Jacobian of the system
% this is an anonymous function with a vector input and matrix output
% x0 is a set of initial guesses (in a column vector)
% tol is a tolerance
xold=x0;
xnew=x0-J(x0)^(-1)*(f(x0));
while norm(xnew-xold)>tol
xold=xnew;
xnew=xold-J(xold)^(-1)*f(xold);
end
p=xnew;
end
%code to call function
sysNewton({@(x,y,z)x+y+z-3;x^2+y^2+z^2-5;exp(x)+x*y-x*z-1},({@(x,y,z)1,1,1;2*x,2*y,2*z;y-z+exp(x),x,-x}),[1,0,1],10^-6)
My code is correct however I cannot call the function the way that I want to. I am misunderstanding how to call the function, as I didnt really need to know how to call it to write the script.
3 Comments
Answers (3)
Walter Roberson
on 1 Mar 2019
Edited: Walter Roberson
on 1 Mar 2019
Your J(x0) returns 3 x 3 because of the way you define J. Raising that to power -1 using the ^ operator is inv() but more numerically unstable, and you should always avoid using inv() . You algebraic-matrix-multiply the inverse you calculate by the 3 x 1 matrix, giving a 3 x 1 result. If that was what you wanted then you would be better off coding J(x0)^(-1)*(f(x0)) as J(x0)\f(x0)
So you have a 3 x 1 on the right hand side. And you subtract it from x0, which is 1 x 3. In R2016a and earlier, that would be an error, but in R2016b and later, the effect is as if you had coded
bsxfun(@minus, x0, J(x0)etc)
giving a 3 x 3 result.
Your function will be **less* sensitive to initial guesses if you use the \ operator... but only relatively speaking.
By the way: my calculation is that there is no solution to that system, unless perhaps involving infinity. The first part, x(1) - FirstElementOf(J(x0)\F(x)) gives an equation that is 0 when x(2) = -2*log(2) or when x(2) is infinite. When you substitute in -2*log(2) then the third part, x(3) - ThirdElementOf(J(x0)\F(x)) gives 14/3 .
Muhammad Asif
on 17 Aug 2020
sysNewton(@(x) [x(1)+x(2)+x(3)-3;x(1)^2+x(2)^2+x(3)^2-5;exp(x(1))+x(1)*x(2)-x(1)*x(3)-1],...
@(x) [1,1,1;2*x(1),2*x(2),2*x(3);x(2)-x(3)+exp(x(1)),x(1),-x(1)],[1;0;1],10^-6)
0 Comments
See Also
Categories
Find more on Operators and Elementary Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!