gpt4 book ai didi

python - 如何创建关联矩阵

转载 作者:太空宇宙 更新时间:2023-11-04 10:27:36 27 4
gpt4 key购买 nike

我正在努力创造

[[ 1,  1,  1,  0,  0,  0,  0,  0,  0],
[-1, 0, 0, 1, 1, 0, 0, 0, 0],
[ 0, -1, 0, -1, 0, 1, 1, 0, 0],
[ 0, 0, 0, 0, -1, -1, 0, 1, 0],
[ 0, 0, -1, 0, 0, 0, -1, 0, 1],
[ 0, 0, 0, 0, 0, 0, 0, -1, -1]]

S=[1, 2, 3, 4, 5, 6]
D=[[1, 2], [1, 3], [1, 5], [2, 3], [2, 4], [3, 4], [3, 5], [4, 6], [5, 6]]
INC = [[0]*len(D) for _ in range(len(S))]

for i in range(len(D)):

在这之后我做错了,我得到了一个零矩阵

    for j in S:
if i == j:
INC.append(1)

我试过将 D 放入两个不同的列表中,这对我来说开始变得复杂了

my_list1 = [i[0] for i in D]
my_list2 = [i[1] for i in D]

最佳答案

我对你想要什么的最佳猜测...你的变量名很差。我会用 NetworkX (networkx)让它做所有的数学运算。

import networkx as nx

nodes = [1, 2, 3, 4, 5, 6]
edges = [[1, 2], [1, 3], [1, 5], [2, 3], [2, 4], [3, 4], [3, 5], [4, 6], [5, 6]]

G = nx.DiGraph()
G.add_nodes_from(nodes)
G.add_edges_from(edges)

incidence_matrix = -nx.incidence_matrix(G, oriented=True)
# ^ this returns a scipy sparse matrix, can convert into the full array as below
# (as long as your node count is reasonable: this'll have that squared elements)
print(incidence_matrix.toarray())

输出:

[[ 1.  1.  1.  0.  0.  0.  0.  0.  0.]
[-1. 0. 0. 1. 1. 0. 0. 0. 0.]
[ 0. -1. 0. -1. 0. 1. 1. 0. 0.]
[ 0. 0. 0. 0. -1. -1. 0. 1. 0.]
[ 0. 0. -1. 0. 0. 0. -1. 0. 1.]
[ 0. 0. 0. 0. 0. 0. 0. -1. -1.]]

关于python - 如何创建关联矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28549762/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com