function [ranking, vector] = pagerank1(E)
% PAGERANK1 : compute page rank from adjancency matrix
%
% [ranking, vector] = pagerank1(E)
%
% E is a matrix of 0s and 1s, 
% where E(i,j) = 1 means that web page (vertex) j has a link to web page i.
%
% This computes page rank by the following steps:
%  1. Add links from any dangling vertices to all vertices.
%  2. Scale the columns to sum to 1.
%  3. Add a constant matrix to represent jumping at random 15% of the time.
%  4. Find the dominant eigenvector with the power method.
%  5. Sort the eigenvector to get the rankings.
%
% The homework problem due February 24 asks you to rewrite this code
% so it never creates a full matrix, or any large matrix other than E.


[nrows,n] = size(E);
if nrows ~= n
    error('E must be square'); 
end;
if (max(max(E)) ~= 1) || (sum(sum(E)) ~= nnz(E))
    error('E must contain only zeros and ones');
end;

%  1. Add links from any dangling vertices (danglers) to all vertices.
%     Note: This is a different way of doing this than we used in class.
e = ones(n,1);         % vector of all 1's
d = zeros(n,1);        % vector of all 0's
outdegree = sum(E);
for j = 1:n
    if outdegree(j) == 0
        d(j) = 1;
    end;
end;                   % d(j) is now 1 if j is a dangler

F = E + e*d';  % e*d' is an n-by-n matrix with all-1 columns for danglers.

%  2. Scale the columns to sum to 1.
A = F * diag(1 ./ sum(F));

%  3. Add a constant matrix to represent jumping at random 15% of the time.
S = ones(n)/n;
m = 0.15;
M = (1-m) * A + m*S;

%  4. Find the dominant eigenvector.
v = e / n;    % Start with a vector all of whose entries are 1/n.
oldv = zeros(n,1);
iters = 0;

while norm(v-oldv) > 1e-6
    oldv = v;
    v = M*v;
    lambda = norm(v);
    v = v / lambda;
    iters = iters + 1;
end;

fprintf('Dominant eigenvalue is %f after %d iterations.\n', lambda, iters);
vector = v;
    
%  5. Sort the eigenvector to get the rankings.
[ignore, ranking] = sort(vector,'descend');