简体   繁体   中英

Graph Edges intialization between nodes using numpy?

Let's say I have to initialise the bi-directional edges for the following graph between the nodes:

在此处输入图像描述

I can easily do this using the following code:

import numpy as np
node_num = 3
graph = np.ones([node_num, node_num]) - np.eye(node_num)

Now I am extending this graph in the following way:

在此处输入图像描述

What is the simple and efficient way to make it code for this graph?

Assuming you're looking for an adjacency matrix, you could use:

out = np.block([
    [1 - np.eye(3), np.eye(3)       ],
    [    np.eye(3), np.zeros((3, 3))]
]).astype(int)

out:

array([[0, 1, 1, 1, 0, 0],   # A
       [1, 0, 1, 0, 1, 0],   # B
       [1, 1, 0, 0, 0, 1],   # C
       [1, 0, 0, 0, 0, 0],   # BC
       [0, 1, 0, 0, 0, 0],   # AB
       [0, 0, 1, 0, 0, 0]])  # AB(red)

but I would suggest you just initialize it as the outputted adjacency matrix. I would only use a short one liner for very simple graphs like your first image, not the second.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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