-1

How to convert adjacency list to adjacency matrix via matab

For example: Here is the adjacency list(undirected), the third column is the weight.

1 2 3
1 3 4
1 4 5
2 3 4
2 5 8
2 4 7

++++++++++++++++++++++

that should be converted to:

   1  2  3  4  5  

1     0  4  5  0   
2  3     4  7  8  
3  4  7     0  0  
4  0  7  0     0  
5  0  8  0  0
Shai
  • 111,146
  • 38
  • 238
  • 371
Jusleong
  • 113
  • 3
  • 5
  • 10
  • 1
    Why isn't the diagonal zero? And if you consider undirected connections, the matrix has to be symmetric. – Fraukje Oct 10 '13 at 12:40
  • 1
    I reformatted your matrix... is that what you were after? Why isn't it symmetrical? – Dan Oct 10 '13 at 12:45

2 Answers2

4

You can use sparse matrix. Let rows be the first column, cols the second, and s the weight.

A = sparse([rows; cols],[cols; rows],[s; s]);

If you want to see the matrix. use full().

UPDATE:

I made the answer a bit simpler (everything in one line, instead of adding the transposed, and included explanations, as requested:

list = [1 2 3
1 3 4
1 4 5
2 3 4
2 5 8
2 4 7];

rows = list(:,1)
cols = list(:,2)
s = list(:,3)

Now, rows, cols and s contains the needed information. Sparse matrices need three vectors. Each row of the two first vectors, rows and cols is the index of the value given in the same row of s (which is the weight).

The sparse command assigns the value s(k) to the matrix element adj_mat(rows(k),cols(k)).

Since an adjacency matrix is symmetric, A(row,col) = A(col,row). Instead of doing [rows; cols], it is possible to first create the upper triangular matrix, and then add the transposed matrix to complete the symmetric matrix.

A = sparse([rows; cols],[cols; rows],[s; s]);    
full(A)

A = 
   0   3   4   5   0
   3   0   4   7   8
   4   4   0   0   0
   5   7   0   0   0
   0   8   0   0   0
Stewie Griffin
  • 14,889
  • 11
  • 39
  • 70
0

It's really hard to tell what your'e asking. Is this right?

list = [1 2 3
1 3 4
1 4 5
2 3 4
2 5 8
2 4 7];


matrix = zeros(max(max(list(:, 1:2))));  %// Or just zeros(5) if you know you want a 5x5 result

matrix(sub2ind(size(matrix), list(:,1), list(:,2))) = list(:,3);  %// Populate the upper half
matrix = matrix + matrix'  %'// Find the lower half via symmetry

matrix =

   0   3   4   5   0
   3   0   4   7   8
   4   4   0   0   0
   5   7   0   0   0
   0   8   0   0   0
Dan
  • 45,079
  • 17
  • 88
  • 157