稀疏矩阵到ijv格式

2024-10-04 07:38:15 发布

您现在位置:Python中文网/ 问答频道 /正文

是否有一种有效的方法将稀疏矩阵表示为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,0,3,0,4],[0,0,5,7,0],[0,0,0,0,0],[0,2,6,0,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_矩阵给我:

print(coo_matrix([[0,0,3,0,4],[0,0,5,7,0],[0,0,0,0,0],[0,2,6,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)

我最后也是这么想的


Tags: of方法inforsizenprange矩阵