2021-05-07 17:04

# python生成的矩阵以固定数目赋值

```import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
import random

#无向图
BA=nx.barabasi_albert_graph(5,1)#barabasi_albert_graph(n, m)方法生成一个含有n个节点、每次加入m条边的BA无标度网络
n = nx.number_of_nodes(BA)
m = nx.number_of_edges(BA)
# print(n,m)
matrix = nx.to_numpy_matrix(BA)
matrix_up = np.triu(matrix)#取矩阵的上三角
num = 0
for i in range(n):
for j in range(n):
if matrix_up[i][j] != 0:
num = num +1
matrix_up[i][j] = random.randint(1,9)
print('改变后的邻接矩阵：\n',matrix_up)```

• 点赞
• 写回答
• 关注问题
• 收藏
• 邀请回答

#### 2条回答默认 最新

• 天元浪子 2021-05-07 21:50
已采纳
``````>>> import numpy as np
>>> arr = np.random.randint(0, 2, (4,5)) # 测试用的矩阵，只有0和1两种元素
>>> arr
array([[1, 0, 1, 0, 1],
[1, 0, 1, 1, 0],
[0, 0, 0, 1, 1],
[1, 0, 1, 0, 0]])
>>> rows, cols = np.where(arr>0) # 找出非零元素的行和列
>>> rows
array([0, 0, 0, 1, 1, 1, 2, 2, 3, 3], dtype=int64)
>>> cols
array([0, 2, 4, 0, 2, 3, 3, 4, 0, 2], dtype=int64)
>>> choices = np.arange(rows.shape[0]) # 非零元素编号
>>> group_1 = np.random.choice(choices, size=3, replace=False) # 随机选中3个分为一组
>>> group_2 = np.setdiff1d(choices, group_1) # 剩余为另一组
>>> group_1
array([4, 2, 1])
>>> group_2
array([0, 3, 5, 6, 7, 8, 9])
>>> arr[(rows[group_1], cols[group_1])] = np.random.randint(1,4) # 第1组赋值
>>> arr[(rows[group_2], cols[group_2])] = np.random.randint(4,11) # 第2组赋值
>>> arr
array([[6, 0, 2, 0, 2],
[6, 0, 2, 6, 0],
[0, 0, 0, 6, 6],
[6, 0, 6, 0, 0]])``````
点赞 1 评论
• 天元浪子 2021-05-08 09:40
``````>>> import numpy as np
>>> arr = np.random.randint(0, 2, (4,5)) # 测试用的矩阵，只有0和1两种元素
>>> arr
array([[0, 1, 0, 1, 1],
[1, 1, 1, 0, 1],
[0, 0, 0, 1, 0],
[0, 0, 0, 1, 0]])
>>> rows, cols = np.where(arr>0) # 找出非零元素的行和列
>>> choices = np.arange(rows.shape[0]) # 非零元素编号
>>> group_1 = np.random.choice(choices, size=3, replace=False) # 随机选中3个分为一组
>>> group_2 = np.setdiff1d(choices, group_1) # 剩余为另一组
>>> for i, j in zip(rows[group_1], cols[group_1]):
arr[i,j] = np.random.randint(1,4)

>>> for i, j in zip(rows[group_2], cols[group_2]):
arr[i,j] = np.random.randint(4,11)

>>> arr
array([[0, 4, 0, 6, 1],
[1, 7, 4, 0, 9],
[0, 0, 0, 3, 0],
[0, 0, 0, 9, 0]])``````
点赞 1 评论