function[r,niter]=NR(f,J,x0,tol,rerror,maxiter)
%Zerorofthenonlinearsystemofequationsf(x)=0.
%HereJistheJacobianmatrixoffandx0istheinitial
%approximationofthezeror.
%Computationsareinterruptedeitherifthenormof
%fatcurrentapproximationisless(inmagnitude)
%thanthenumbertol,oriftherelativeerroroftwo
%consecutiveapproximationsissmallerthantheprescribed
%accuracyrerror,orifthenumberofallowediterations
%maxiterisattained.
%Thesecondoutputparameterniterstandsforthenumber
%ofperformediterations.
Jc=rcond(feval(J,x0));
ifJc<1e10
error('Tryanewinitialapproximationx0')
end
xold=x0(:);
xnew=xoldfeval(J,xold)\feval(f,xold);
fork=1:maxiter
xold=xnew;
niter=k;
xnew=xoldfeval(J,xold)\feval(f,xold);
if(norm(feval(f,xnew))<tol)|...
norm(xoldxnew,'inf')/norm(xnew,'inf')<tol|...
(niter==maxiter)
break
end
end
r=xnew;
has the exact zeros r = [0 1]T and r = [2 0]T (see [6], p. 166). Functions fun1 and J1 define the
system of equations and its Jacobian, respectively
functionz=fun1(x)
z=zeros(2,1);
z(1)=x(1)+2*x(2)2;
z(2)=x(1)^2+4*x(2)^24;
functions=J1(x)
s=[12;2*x(1)8*x(2)];
Let
x0=[00];
Then
[r,iter]=NR('fun1','J1',x0,eps,eps,10)
???Errorusing==>nr
Tryanewinitialapproximationx0
For x0 as chosen above the associated Jacobian is singular. Let's try another initial guess for r
x0=[10];
[r,niter]=NR('fun1','J1',x0,eps,eps,10)
r=
2.00000000000000
0.00000000000000
niter=
5
Consider another nonlinear system
f1(x) = x1 + x2 1
f2(x) = sin(x1 + x2 ) x1.
2 2
The m-files needed for computing its zeros are named fun2 and J2
functionw=fun2(x);
w(1)=x(1)+x(2)1;
w(2)=sin(x(1)^2+x(2)^2)x(1);
w=w(:);
functions=J2(x)
s=[11;
2*x(1)*cos(x(1)^2+x(2)^2)12*x(2)*cos(x(1)^2+x(2)^2)];