【发布时间】:2015-03-19 20:08:51
【问题描述】:
我想在 python 中创建一个 nxn 对称矩阵。假设 n=9,那么我想要如下所示:
array[[0,1,0,0,0,1,1,0,1],[1,0,1,1,1,0,0,0,0],[0,1,0,1,1,0,0,0,0]….].
我知道如何做到这一点,首先在 python (np.zeros((9,9)) 中创建一个修女零矩阵,然后使用循环填充它 1 和零。但我觉得这不是 python 的方式. 因此,如果矩阵很大,正在寻找一种使用循环的优化方式会减慢代码。
基本上这是我为无向图创建的邻接矩阵。我的后续问题是如何绘制具有邻接矩阵的图形。任何从邻接矩阵绘制无向图的函数?
请指教。我想学习在 python 中做某事而不是使用传统循环的最佳优化/pythonic 方式。
编辑:
我使用以下内容为 30x30 邻接矩阵创建边列表。但是这个边缘列表没有集群中每个节点的对。如果我开始这样做,列表将是巨大的。因此,我下面的图表在集群中的每个节点之间没有边。如何自动化这个边缘列表,这样我就不必手动输入所有边缘对。在图中,我希望集群中的每个节点都与该集群中的其他节点有一条边,并且只有节点 1 和 2 应该在集群边缘与其他集群的节点 16 和 17 之间。
N=30
# Creating a matrix of zeros.
W=np.zeros((N,N))
# Mentioning the edges to start with. Thinking of a pair of 15 node cluster with two cluster connected by two pair of nodes.
edge=[[1,2],[1,3],[1,4],[1,5],[1,6],[1,7],[1,8],[1,9],[1,10],[1,11],[1,12],[1,13],[1,14],[1,15],
[16,17],[16,18],[16,19],[16,20],[16,21],[16,22],[16,23],[16,24],[16,25],[16,26],[16,27],[16,28],[16,29],[16,30],
[1,16],[2,17]]
# Function for creating adjacency matrix ,populating the zeros matrix with 1 and 0-signifying edges on a node.
def adjacencyMatrix():
"""This function creates an Adjacency Matrix from a edge set.
input-> set of edges to be connected
output-> Adjacency matrix (n,n)
"""
for first,second in edge:
W[first-1,second-1]=W[second-1][first-1]=1
图表:
【问题讨论】:
-
您对图表有什么样的访问权限?显然,
is_adjacent(source_node, target_node)-type 函数是必需的,但是您是否有一个get_neighbors(source_node)-type 函数可以返回相邻的 target_nodes 列表?这可以用来加快速度。
标签: python numpy pandas matplotlib