0

I am trying to calculate the laplacian matrix of a graph. I ve calculated the sparse representation of the adjacency matrix which is stored in a text file with dimension Nx3. N the size of nodes (ith-node jth node weight). I open in Matlab this file with adj = spconvert(adj);. The next step is to calculate the degree matrix of this sparse matrix in order to perform the operation L = D - adj. How is it possible to calculate the degree matrix having as an input the sparse adjacency matrix of the graph? In order to calculate the degree matrix I calculate the degree for every node:

for i=1:n % size of the node
    degree(i) =  length(find(adj(:,1) == i & adj(:,3) == 1));
end

However, how can I perform the subtraction of D and A?

snake plissken
  • 2,649
  • 10
  • 43
  • 64

1 Answers1

2

Use the spdiags function to convert the degree vector to a sparse diagonal matrix. Then subtract the adjacency matrix from diagonal matrix to get the Laplacian. Example using your code:

adj = spconvert(adj);
for i=1:size(adj, 1)
    degree(i) = CalcDegree(adj, i)
end
D = spdiags(degree, 0, size(adj, 1), size(adj, 2));
L = D - adj;

By the way, your code for calculating the node degree may be incorrect.

nojka_kruva
  • 1,454
  • 1
  • 10
  • 23
  • Degree matrix size is the size of of nodes. however the adj matrix has different size which is the number of edges. With the CalcDegree I guess you mean my method. I am getting problems with spdiags ??? Index exceeds matrix dimensions. Error in ==> spdiags at 114 a((len(k)+1):len(k+1),:) = [i i+d(k) B(i+(m>=n)*d(k),k)]; – snake plissken Jun 19 '14 at 11:07
  • Your code for calculating the node degree fits the 3-column representation of the adjacency matrix in the text file, not the representation after parsing the text file with spconvert, which should be a matrix whose number of rows and columns equals the number of vertices, not the number of edges (en.wikipedia.org/wiki/Adjacency_matrix). This also should be the reason you are getting incorrect dimensions. – nojka_kruva Jun 19 '14 at 11:21
  • Yea you are right, but I calculate the sparse representation of the adjacency matrix. Thus, instead of having a NxN matrix I ve just have the active set of edges. – snake plissken Jun 19 '14 at 11:25
  • 1
    No need for that. Matlab stores sparse matrices efficiently in its sparse matrix object type, which you get by using spconvert. – nojka_kruva Jun 19 '14 at 11:27
  • Ok I like your comment, however degree it has to be calculated using the initial sparse representation? – snake plissken Jun 19 '14 at 11:34
  • You can calculate the degree of the i'th node in the matrix representation by summing the elements (or counting the nonzero elements) in the i'th column. – nojka_kruva Jun 19 '14 at 12:18