function [lambda, x, iter] = smalleig(A, x0, tol, numiter)
%smalleig: inverse power method for computing the smallest eigenvalue
%of a matrix in magnitude
%
%   [lambda x iter] = smalleig(A,x0,n,tol) computes the smallest eigenvalue
%   lambda in magnitude and corresponding eigenvector x of real matrix A
%   using the inverse power method. x0 is the initial approximation,
%   tol is the desired error tolerance, and maxiter is the maximum number
%   of iterations to perform. If the algorithm converges, iter contains
%   the number of iterations required.
%   If the method does not converge, iter = -1.

   [m, n] = size(A);
   if m ~= n
      disp('The matrix is not square.');
      return;
   end
   
   xprev = x0/norm(x0);
   [L, U, P] = ludecomp(A);

   for i = 1:numiter
      % generate the next approximation
      xnew = lusolve(L,U,P,xprev);
      xnew = xnew/norm(xnew);
      lambda = xnew'*(A*xnew);
      if norm(A*xnew-lambda*xnew) < tol
         iter = i;
         x = xnew;
         return;
      end
      xprev = xnew;
   end
   
   iter = -1;
   x = xnew;
