Advertisement
Bkmz

Untitled

Apr 16th, 2012
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 0.81 KB | None | 0 0
  1. function [xopt, fopt, niter, gnorm, dx ] = grad_descent2(varargin)
  2. if nargin==0
  3.  
  4.  x0 = [3,3];
  5. elseif nargin==1
  6.  x0 = varargin{1};
  7. end
  8.  
  9. tol = 1e-6;
  10. maxiter = 1000;
  11. dxmin = 1e-6;
  12. alpha = 0.1;
  13.  
  14. gnorm = inf; x=x0; niter=0; dx=inf;
  15.  
  16. f = @(x1,x2) x1.^2+x1.*x2+3*x2.^2;
  17. figure(1); clf; ezcontour(f, [-5 5 -5 5]); axis equal; hold on
  18. f2 = @(x) f(x(1),x(2));
  19.  
  20. while and(gnorm>=tol, and(niter<=maxiter, dx>=dxmin))
  21.  
  22.     g=grad(x);
  23.     gnorm=norm(g);
  24.  
  25.     xnew = x - alpha*g;
  26.  
  27. %    if -isfinite(xnew)
  28. %        niter
  29. %        error('x is inf or NaN');
  30.     end
  31.  
  32.     plot([x(1) xnew(1)], [x(2) xnew(2)], 'o')
  33.     reflesh
  34.     niter = niter + 1;
  35.     dx = norm(xnew - x);
  36.     x = xnew;
  37. end
  38. xopt = x
  39. fopt = f2(xopt);
  40. niter = niter - 1;
  41.  
  42. function g = grad(x)
  43. g=[2*x(1) + x(2)
  44. x(1) + 6*x(2)];
  45.  
  46. end
  47. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement