function [lambda, x, iter] = largeeig(A, x0, tol, maxiter)
%LARGEEIG: power method for computing the largest eigenvalue of a matrix.
%
%   [lambda x iter] = largeeig(A,x0,tol,maxiter) computes the largest eigenvalue
%   lambda in magnitude and corresponding eigenvector x of real matrix A
%   using the power method. x0 is the initial approximation, tol is the
%   desired error tolerance, and maxiter is the user-supplied number
%   of iterations. 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);

for i = 1:maxiter
	% generate the next approximation
	xnew = A*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;