function [pi,time,numiter]=pagerank(pi0,H,n,alpha,epsilon);

% PAGERANK  computes the PageRank vector for an n-by-n Markov  
%           matrix H with starting vector pi0 (a row vector) 
%           and scaling parameter alpha (scalar).  Uses power 
%           method.
%
% EXAMPLE: [pi,time,numiter]=pagerank(pi0,H,1000,.9,1e-8);
%
% INPUT: 			pi0 = starting vector at iteration 0 (a row vector)
%         H = row-normalized hyperlink matrix (n-by-n sparse matrix)
%         n = size of H matrix (scalar)
%         alpha = scaling parameter in PageRank model (scalar)
%         epsilon = convergence tolerance (scalar, e.g. 1e-8)
%
% OUTPUT:   pi = PageRank vector 
%           time = time required to compute PageRank vector
%           numiter = number of iterations until convergence
%
% The starting vector is usually set to the uniform vector, 
% pi0=1/n*ones(1,n).
% NOTE: Matlab stores sparse matrices by columns, so it is faster  
%       to do some operations on H', the transpose of H.


% get "a", the dangling node vector, where a(i)=1, if node i 
%   is dangling node and 0, o.w.

rowsumvector=ones(1,n)*H';
nonzerorows=find(rowsumvector);
zerorows=setdiff(1:n,nonzerorows); l=length(zerorows);
a=sparse(zerorows,ones(l,1),ones(l,1),n,1);


k=0;
residual=1;
pi=pi0;
tic;

while (residual >= epsilon) 
  prevpi=pi;
  k=k+1;
  pi=alpha*pi*H + (alpha*(pi*a)+1-alpha)*((1/n)*ones(1,n));
  residual=norm(pi-prevpi,1);
end
numiter=k;
time=toc;