function ShowPageRank()
clc
n = 1000;
% Generate an nxn matrix G in which G(i,j) = 1 if there is a link from
% page j to page i.
G = sparse(n,n);
for j=1:n
% Page j will have roughly this many outlinks..
nOutlinks = max(0,floor(10*(1+randn(1))));
v = sprand(n,1,nOutlinks/n);
G(:,j) = ceil(v);
end

% Compute the PageRank...
alfa = .85;
PR = PageRank(G,alfa);
% Display top 10 via PageRank and top ten via InLink rank...
Top10PR = PR(1:10);
[z,InLink] = sort(sum(G')','descend');
Top10IN = InLink(1:10);
disp(' PR IN')
disp([Top10PR Top10IN])

function PR = PageRank(G,alfa)
% G is an nxn link-structure matrix in sparse format.
% 0<=alfa<=1
% PR is a column n-vector with the property that PR(i) is the page rank
% of webpage i,i=1:n.

% Compute the eigenvector x (nonnegative enties) so Tx = x where T is
% the nxn stochastic matrix defined by
% e/n if G(:,k) = zeros(n,1)
% T(:,k) =
% (1-alfa)*e/n + alfa*G(:,k)/sum(G(:,k)) otherwise

[n,n] = size(G);
[q,lambda] = eigs(@(x) MyProd(x,G,alfa),n,1);
q = abs(q);
[z,PR] = sort(q,'descend');

function y = MyProd(x,G,alfa)
% G is the link matrix
% Carries out the matrix vector product y = Tx where T is the nxn defined by
% e/n if sum(G(:,j)) = 0
% T(:,j) =
% alfa*G(:,j)/sum(G(:,j)) + (1-alfa)*e/n
%
% where
n = length(x); e = ones(n,1);
% Compute y as a linear combination of T's columns...
y = zeros(n,1);
for j=1:n
d = sum(G(:,j));
if d==0;
y = y + x(j)*e/n;
else
col = (1-alfa)*e/n + alfa*G(:,j)/d;
y = y +x(j)*col;
end
end