在系统工程书中,建立解释结构模型中求解可达矩阵是必不可少的一环
故利用python写了一段求解可达矩阵的代码,只需要输入邻接矩阵便可计算得到可达矩阵
代码如下:
import numpy as np
def change(a): #乘自身并归一
b=np.dot(a,a)
m=a.shape
for i in range(m[0]):
for j in range(m[1]):
if b[i,j]!=0:
b[i,j]=1
return b
def unit(n): #生成n维单位矩阵
a=np.zeros((n,n))
for i in range(n):
for j in range(n):
if i==j:
a[i,j]=1
return a
def keda(b): #生成可达矩阵
m=b.shape
unit_b=unit(m[0])
K1=b+unit_b
for i in range(m[0]):
KN=change(K1)
if np.array_equal(KN,K1)==True:
break
K1=KN
print(KN)
return KN
#################################################
A=np.array([[0,0,0,0,0,0,0,0,0,0],
[1,0,1,1,0,0,0,0,0,1],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[1,0,0,0,0,1,0,0,0,0],
[1,0,0,0,1,0,0,0,0,0],
[1,1,0,0,0,0,0,1,0,0],
[1,0,1,1,0,0,0,0,0,1],
[1,1,0,1,1,1,0,1,0,0],
[1,0,1,1,0,0,0,1,0,0]],dtype=int)
keda(A)
可以得到运算结果
可达矩阵结果.PNG
网友评论