简体   繁体   English

在 Python 中修改邻接矩阵

[英]Modifying the adjacency matrix in Python

The code generates adjacency matrix of 3x3 network where diagonals are not connected.该代码生成对角线未连接的3x3网络的邻接矩阵。 I want the code to generate adjacency matrix of connected diagonals.我希望代码生成连接对角线的邻接矩阵。 I present the current and expected output.我介绍了当前和预期的输出。

import networkx as nx
G = nx.grid_2d_graph(3,3)
nodes = {n: i for i, n in enumerate(G.nodes, start=1)}
edges = {i: e for i, e in enumerate(G.edges, start=1)}
A1 = nx.adjacency_matrix(G)
A = A1.toarray()
G = nx.convert_node_labels_to_integers(G)
G = nx.relabel_nodes(G, {node: node+1 for node in G.nodes})
nx.draw(G, with_labels=True, pos=nx.spring_layout(G))
A1 = nx.adjacency_matrix(G)
A = A1.toarray()

The current output is当前输出为

array([[0, 1, 0, 1, 0, 0, 0, 0, 0],
       [1, 0, 1, 0, 1, 0, 0, 0, 0],
       [0, 1, 0, 0, 0, 1, 0, 0, 0],
       [1, 0, 0, 0, 1, 0, 1, 0, 0],
       [0, 1, 0, 1, 0, 1, 0, 1, 0],
       [0, 0, 1, 0, 1, 0, 0, 0, 1],
       [0, 0, 0, 1, 0, 0, 0, 1, 0],
       [0, 0, 0, 0, 1, 0, 1, 0, 1],
       [0, 0, 0, 0, 0, 1, 0, 1, 0]], dtype=int32)

在此处输入图像描述

The expected output is预期的输出是

array([[0, 1, 0, 1, 1, 0, 0, 0, 0],
       [1, 0, 1, 1, 1, 1, 0, 0, 0],
       [0, 1, 0, 0, 1, 1, 0, 0, 0],
       [1, 0, 0, 0, 1, 0, 1, 1, 0],
       [0, 1, 0, 1, 0, 1, 1, 1, 1],
       [0, 0, 1, 0, 1, 0, 0, 1, 1],
       [0, 0, 0, 1, 1, 0, 0, 1, 0],
       [0, 0, 0, 1, 1, 1, 1, 0, 1],
       [0, 0, 0, 0, 1, 1, 0, 1, 0]], dtype=int32)

在此处输入图像描述

You can add an edge for every non-last node in 2D grid.您可以为 2D 网格中的每个非最后一个节点添加一条边。 Also you can easily extend the solution for a non square case.您还可以轻松地将解决方案扩展到非方形案例。

n = 3    
G = nx.grid_2d_graph(n,n)

iifrom = jjfrom = range(n-1)
nnfrom = [(ifrom,jfrom) for ifrom in iifrom for jfrom in jjfrom]
nnto = [(ifrom+1,jfrom+1) for ifrom in iifrom for jfrom in jjfrom]
nnfrom += [(ifrom+1,jfrom) for ifrom in iifrom for jfrom in jjfrom]
nnto += [(ifrom,jfrom+1) for ifrom in iifrom for jfrom in jjfrom]
G.add_edges_from(zip(nnfrom, nnto))

G = nx.convert_node_labels_to_integers(G)
G = nx.relabel_nodes(G, {node: node+1 for node in G.nodes})
A1 = nx.adjacency_matrix(G)
A = A1.toarray()

print(A)
nx.draw(G, with_labels=True)

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

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