Search code examples
matlabmatrixsparse-matrixadjacency-matrix

Using sparse matrix as adjacency matrix in MATLAB


I have a file which contains the following directed graph:

1 2
2 4
3 1
2 3

Each number is considered as a node in the graph.
Each node in the first column has a forwarding edge to its front node in the second column.
I want to make an adjacency matrix for this graph.
I should use a sparse matrix for that matter.
Here is the problem:
As you can see in the graph, node 4 has no edges to other nodes, thus my sparse adjacency matrix will not be square.

Here is my code for making the matrix:

adj = sparse(Graph(:,1),Graph(:,2),1);

How can I store the 4th row in this matrix?


Solution

  • Set the size you want:

    n=max(Graph(:));
    adj = sparse(Graph(:,1),Graph(:,2),1,n,n);