如何解决稀疏矩阵转ijv格式
是否有一种有效的方法可以将稀疏矩阵表示为 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 举报,一经查实,本站将立刻删除。