不能保證能各個節點之間能完全走通,只是記錄一下。
import numpy as np
def structMatrix(n=11, low=1, high=10, num_base=10, num_more=10):
"""
構建無向圖鄰接矩陣
:param n: 矩陣是 n x n 狀的
:param low: 矩陣中每個位置數值的大小下限
:param high: 矩陣中每個位置數值的大小上限
:param num_base:要替換的數量下限
:param num_more:要替換的數量增加值(下限 + 增加值 = 上限,下限 + 增加值*random = 要替換的數量確定值)
:return:
"""
# k = np.random.rand()
X_ = np.random.randint(low=low,high=high,size=n**2).reshape(n,n).astype(float) # 先造一個n*n的浮點矩陣(整數型矩陣無法放np.inf)
# 在行索引中隨機選擇num_base到num_base+num_more個(如10到10+10個)用於後面替換成np.inf(因爲可能有大量重複,所以你可以設的base和more都可以大些)
index_0 = np.random.choice(X_.shape[0], int(num_base + num_more * np.random.rand()))
print(f"index_0={index_0}")
# 在列索引中隨機選擇num_base到num_base+num_more個(如10到10+10個)用於後面替換成np.inf(因爲可能有大量重複,所以你可以設的base和more都可以大些)
index_1 = np.random.choice(X_.shape[1], int(num_base + num_more * np.random.rand()))
print(f"index_1={index_1}")
# 將行列索引組合起來,每次根據一個行座標和一個列座標確定一個座標,對應元素設置爲np.inf
print("下面是初次選中的座標:")
for (i,j) in list(zip(index_0, index_1)):
print((i,j))
# 如果在對角線上就不替換了,因爲對角線上應該是0的(或者你可以設置1e-4這種很小的數,這取決於你的程序)
if i == j:
continue
X_[i,j] = np.inf
X_ = np.triu(X_) # 得到原X的上三角矩陣(含對角線),下三角清零
X_ += X_.T - 2*np.diag(X_.diagonal()) # X.diagonal()提取對角線,np.diag()構造對角線矩陣,再減去該2倍對角線矩陣得對角線爲0的矩陣
return X_
print(f"結果矩陣:\n{structMatrix()}")