Page 287 - MATLAB an introduction with applications
P. 287
272 ——— MATLAB: An Introduction with Applications
h=1e–5; TolFun=eps; EPS=1e–6;
fx=feval(f,x0,varargin{:});
Nf=length(fx); Nx=length(x0);
if Nf~=Nx, error(‘Incompatible dimensions of f and x0!’); end
if nargin<4, MaxIter=100; end
if nargin<3, TolX=EPS; end
xx(1,:)=x0(:).’;
%fx0= norm(fx);
for k=1: MaxIter
J=jacob(f,xx(k,:),h,varargin{:});
if rank(J)<Nx
k=k–1; fprintf(‘Warning: Jacobian singular! with det(J)=%12.6e\n’,det(J));
break;
else
dx= –J\fx(:); %–[dfdx]^–1*fx;
end
xx(k+1,:)= xx(k,:)+dx.’;
fx= feval(f,xx(k+1,:),varargin{:}); fxn=norm(fx);
% if fxn<fx0, break; end
%end
if fxn<TolFun|norm(dx)<TolX, break; end
%fx0= fxn;
end
x= xx(k+1,:);
if k==MaxIter
fprintf(‘Do not depend on this, though the best in %d iterations\n’,MaxIter)
end
Example E5.2: Minimize the two-variable objective function
2
f (x , x ) = x – 2x x – 4x + x – x 2
2
2
1
1 2
1
2
1
Use initial values: (0,0).
Solution:
>> fn=inline(’10*x(1)^2–10*x(1)*x(2)+3*x(2)^2+2*x(1)’,‘x’);
>> gn=inline(‘[20*x(1)–10*x(2)+2 –10*x(1)+6*x(2)]’,‘x’);
>> x0=[0 0];TolX=1e–4;TolFun=1e–6;MaxIter=50;
>> [x0,g0,xx]=newtons(gn,x0,TolX,MaxIter)
x0=
–0.6000 –1.0000
g0=
0 0