Reputation: 2234
How can I construct adjacency matrix from input dataset graph file, which has the following data:
The first line of the dataset file, represents the number of nodes and edges resp. The following lines represent node1 and node2 denoting an edge existing between them For example: amazon.graph dataset file contains the following
Below is the file amazon.graph
4 6 // number of nodes and edges
0 1 // edge between node 0 and 1
1 3
2 3
1 2
0 2
0 3
This data is contained in a file named "amazon.graph". I need help with a matlab function that can read the file and build adjacency matrix from the dataset file
Upvotes: 1
Views: 2461
Reputation: 112669
Use sparse
to build the matrix:
x = [4 6
0 1
1 3
2 3
1 2
0 2
0 3]; %// data
adjMatrix = sparse(x(2:end,1)+1, x(2:end,2)+1, 1, x(1,1), x(1,2));
This produces a sparse matrix. You can convert to full form if needed:
adjMatrix = full(adjMatrix);
In your example, this gives
adjMatrix =
0 1 1 1 0 0
0 0 1 1 0 0
0 0 0 1 0 0
0 0 0 0 0 0
To make the graph symmetric (undirected):
s = max(x(1,1), x(1,2)); %// take largest dimemsion
adjMatrix = sparse(x(2:end,1)+1, x(2:end,2)+1, 1, s, s); %// now matrix is square
adjMatrix = adjMatrix | adjMatrix.'; %'// apply "or" with transpose to make symmetric
adjMatrix = full(adjMatrix); %// convert to full if needed
If you have the data in a file, you can read it into the variable x
using textread
. For example, if the file data.txt
contains the text
4 6
0 1
1 3
2 3
1 2
0 2
0 3
just use
x = textread('data.txt');
Then you can apply the above to generate the adjMatrix
from x
.
Upvotes: 3