Using the below code, please implement the algorithm for computing PageRank in M
ID: 3756476 • Letter: U
Question
Using the below code, please implement the algorithm for computing PageRank in Matlab. You will need to complete the lines marked with "******".
---------------------------------------------------------------
function PageRank_incomplete
% This function implements the PageRank algorithm.
dbstop if error; clear; clc; close all;
dDecayFactor = 0.85;
mAdjacencyMatrix = [
0 1 0 0 0; % node 1
0 0 1 1 0; % node 2
0 0 0 1 0; % node 3
1 0 0 0 1; % node 4
0 0 1 0 0; % node 5
];
nNumOfNodes = size(mAdjacencyMatrix,1);
% Node degree matrix
vNodeDegree = sum(mAdjacencyMatrix,2);
mNodeDegreeMatrix = diag(vNodeDegree);
mNodeDegreeMatrixInv = pinv(mNodeDegreeMatrix);
% Compute the node transition probability matrix
mNodeTransProbMatrixP = ; % Please complete this line******
% Compute the PageRank values by using the matrix inverse
mPRMatrix = ; % Please complete this line******
vPRVector1 = sum(mPRMatrix,2) / nNumOfNodes;
disp("Method 1: Matrix Inversion");
disp("PageRank values");
display(vPRVector1);
% Compute the PageRank values by using the iterative method
disp("Method 2: Power Iteration");
vPRVector2 = [];
vTeleportationVector = ones(nNumOfNodes,1) / nNumOfNodes;
vPRVector2_old = vTeleportationVector;
nIdxOfIteration = 0;
while true
vPRVector2_new = ; % Please complete this line******
if norm(vPRVector2_new - vPRVector2_old) < 10^(-6)
vPRVector2 = vPRVector2_new;
disp("# of iterations");
disp(nIdxOfIteration);
break;
end
% Please add one line here******
nIdxOfIteration = nIdxOfIteration + 1;
end
disp("PageRank values");
display(vPRVector2);
figure;
Explanation / Answer
PageRank in MATLAB
A MATLAB implementation of the Google PageRank algorithm :
function [ x ] = PageRank( i, j, n, p )
%PAGERANK Calculates the PageRank of the given network.
% param i: Vector of all nodes which are linked to.
% param j: Vector of all nodes which link to other nodes.
% param n: Number of nodes
% param p: Decay rate (optional)
% Note: Node i[k] links to node j[k].
% Reference: https://www.mathworks.com/moler/exm/chapters/pagerank.pdf
if (~exist('p', 'var'))
p = 0.85;
end
G = sparse(i, j, 1, n, n);
c = sum(G, 1);
k = find(c~=0);
D = sparse(k,k,1./c(k),n,n);
e = ones(n, 1);
I = speye(n, n);
x = (I - p*G*D)e;
x = x/sum(x);
end
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.