close all;
clear all;
clc;

%% Adjacency matrix
A = [   0     1   0 ;
        0     0   1 ;
        1     1   0 ] ;
    
%% No incomming links for node 1    
A = [   0     1   0 ;
        0     0   1 ;
        0     1   0 ] ;    

%% Disconnected graph
A = [   0   1   0   0;
        1   0   0   0;
        0   0   0   1;
        0   0   1   0
        ] ;
    
    
% Create and plot directed graph object
G = digraph(A);
p=plot(G, 'MarkerSize', 10);

%% Number of pages
N = size(A,1);

%% Initial values


% Number of visits for each page
Visits = zeros(N,1);

% Pick random initial page
Page = randi(N);

% Damping factor
d=0.85;

%% Itearate 1000 times
for i=2:1000
    
    %% Increase visits for the current page
    Visits(Page,1) = Visits(Page,1) + 1;
     
    %% Randomly pick a new page from the links going out of the current page
    % L are pages linked by Page
    L=find (A(Page,:)==1);
    % Idx is the index of the link
    Idx = randi(length(L));
    % Next page
    Page = L(Idx);
    
    
    %% Damping factor, the surfer request another random page 15% of the time
    if (rand(1)>d)
        Page = randi(N);
    end
    
    %% Update PageRank
    PR = N*Visits/sum(Visits);
    
    store(i,:) = PR;
end

%% Display final PageRank
PR

%% Plot PageRank evolution
figure;
plot (store, '.-'); 
title ('PageRank vs iterations');
xlabel('Steps');
ylabel('PageRank of each page');
grid on;

%% Add legend
Legend=cell(size(A,1),1);
for i=1:size(A,1)
    Legend{i} = sprintf('Page %d', i);
end
legend(Legend);

