简体   繁体   English

Matlab邻接表到邻接矩阵

[英]matlab adjacency list to adjacency matrix

How to convert adjacency list to adjacency matrix via matab 如何通过Matab将邻接列表转换为邻接矩阵

For example: Here is the adjacency list(undirected), the third column is the weight. 例如:这是邻接表(无向),第三列是权重。

1 2 3 1 2 3
1 3 4 1 3 4
1 4 5 1 4 5
2 3 4 2 3 4
2 5 8 2 5 8
2 4 7 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

You can use sparse matrix. 您可以使用sparse矩阵。 Let rows be the first column, cols the second, and s the weight. rows是第一列, cols第二,和s重量。

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

If you want to see the matrix. 如果要查看矩阵。 use full() . 使用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. 现在, rowscolss包含所需的信息。 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). 两个第一个向量的每一行, rowscolss的同一行中给出的值的索引(即权重)。

The sparse command assigns the value s(k) to the matrix element adj_mat(rows(k),cols(k)) . sparse命令将值s(k)分配给矩阵元素adj_mat(rows(k),cols(k))

Since an adjacency matrix is symmetric, A(row,col) = A(col,row) . 由于邻接矩阵是对称的,因此A(row,col) = A(col,row) Instead of doing [rows; cols] 而不是[rows; cols] [rows; cols] , it is possible to first create the upper triangular matrix, and then add the transposed matrix to complete the symmetric matrix. [rows; cols] ,可以先创建上三角矩阵,然后添加转置矩阵以完成对称矩阵。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM