matlab邻接表到邻接矩阵 [英] matlab adjacency list to adjacency matrix

查看:842
本文介绍了matlab邻接表到邻接矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过matab将邻接列表转换为邻接矩阵

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

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

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

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

应转换为:

   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

推荐答案

您可以使用 sparse 矩阵.假设rows为第一列,cols为第二列,以及s权重.

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]);

如果要查看矩阵.使用full().

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

更新:

我使答案更简单(一切都在一行中,而不是按要求添加移调并包括说明:

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)

现在,rowscolss包含所需的信息.稀疏矩阵需要三个向量. rowscols这两个第一矢量的每一行是s在同一行中给出的值的索引(权重).

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).

sparse命令将值s(k)分配给矩阵元素adj_mat(rows(k),cols(k)).

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

由于邻接矩阵是对称的,因此A(row,col) = A(col,row).代替执行[rows; cols],可以首先创建上三角矩阵,然后添加转置矩阵以完成对称矩阵.

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

这篇关于matlab邻接表到邻接矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆