问题描述
是否有一种有效的方法可以将稀疏矩阵表示为 ijv(3 个数组:行、列、值)形式。 对于大型矩阵,使用嵌套循环似乎非常天真和缓慢。 代码来自here:
# Python program for Sparse Matrix Representation
# using arrays
# assume a sparse matrix of order 4*5
# let assume another matrix compactMatrix
# Now store the value,row,column of arr1 in sparse matrix compactMatrix
sparseMatrix = [[0,3,4],[0,5,7,0],2,6,0]]
# initialize size as 0
size = 0
for i in range(4):
for j in range(5):
if (sparseMatrix[i][j] != 0):
size += 1
# number of columns in compactMatrix(size) should
# be equal to number of non-zero elements in sparseMatrix
rows,cols = (3,size)
compactMatrix = [[0 for i in range(cols)] for j in range(rows)]
k = 0
for i in range(4):
for j in range(5):
if (sparseMatrix[i][j] != 0):
compactMatrix[0][k] = i
compactMatrix[1][k] = j
compactMatrix[2][k] = sparseMatrix[i][j]
k += 1
for i in compactMatrix:
print(i)
# This code is contributed by MRINALWALIA
我打算将稀疏矩阵以 ijv 形式打印到文件中,然后用 C++ 读取它。 scipy.sparse.coo_matrix 给我:
print(coo_matrix([[0,0]]))
(0,2) 3
(0,4) 4
(1,2) 5
(1,3) 7
(3,1) 2
(3,2) 6
使用 np.where()
我可以获得非零元素的索引,但是 v
数组怎么样?
也许你知道一种更有效的方法(我不会使用 swig,...来包装代码)?
编辑
size=np.count_nonzero(sparseMatrix)
rows,cols = np.where(sparseMatrix)
compactMatrix = np.zeros((3,size))
for i in range(size):
compactMatrix[0][i] = rows[i]
compactMatrix[1][i] = cols[i]
compactMatrix[2][i] = sparseMatrix[rows[i]][cols[i]]
print(compactMatrix)
我最后也是这么想的。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)