我将稀疏矩阵的非零值存储在字典中。我如何将其转换为实际矩阵?
def sparse_matrix(density,order):
import random
matrix = {}
for i in range(density):
matrix[(random.randint(0,order-1),
random.randint(0,order-1))] = 1
return matrix
答案 0 :(得分:0)
选项1: 您可以直接创建矩阵并更新其中的值,而不是将值保留在列表中并稍后创建矩阵。 请注意,非零值的数量可以少于“ order”,因为randint可以再次返回相同的数字。
示例代码
import random
import numpy as np
def sparse_matrix(density,order):
#matrix = [ [0 for i in range(order)] for i in range(order)]
matrix = np.zeros((order,order))
for i in range(density):
matrix[(random.randint(0,order-1))][random.randint(0,order-1)] = 1
return matrix
输出:
sparse_matrix(2,4)
array([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 1.]])
选项2
您可以使用代码创建字典,然后使用该字典更新矩阵中的值。
def sparse_matrix(density,order):
import random
#matrix = [ [0 for i in range(order)] for i in range(order)]
matrix = {}
for i in range(density):
matrix[(random.randint(0,order-1)),(random.randint(0,order-1))] = 1
return matrix
#matrix of size order*order
final_matrix = np.zeros((4,4))
for key, value in sparse_matrix(2,4).items() :
final_matrix[key] = value