基于BFS输出如何选择稀疏矩阵元素

时间:2017-12-28 10:57:16

标签: python python-2.7 matrix indexing

我试图基于BFS输出数组逐行选择稀疏矩阵元素。假设我的BFS输出是

[1, 2, 3, 6, 4, 7, 5, 8, 11, 9, 12, 10, 13, 15, 14, 16, 17, 18, 19, 20]

我有一个20x20的稀疏矩阵。

现在我想使用BFS输出作为行索引,并按照与BFS输出数组和绘图相同的顺序从稀疏矩阵中选择非零值。这是我的代码,通过它我可以做一些工作,但不完全是我想要的。

a = numpy.loadtxt('sparsematrix.txt', float, delimiter=',') # import data
y = numpy.reshape(a, np.size(a))
pos = np.delete(y, np.arange(0, y.size, 19))

plt.plot(pos)
plt.xlabel(sample)
plt.ylabel(position)

以上代码的问题是:

  1. 它按行选择每个值,但不按定义的顺序选择 我的BFS输出。 (它应该使用BFS输出数组作为行索引号 一个一个地选择非零值)
  2. 它选择所有值,甚至是零。 - 如何只获得非零值?
  3. 索引从0开始并转到19.我希望索引从1开始。

2 个答案:

答案 0 :(得分:2)

重要更新

现在,通过阅读克里斯蒂安的答案,我得到了你完全想要的东西。我做了另一个功能来补充已经给出的功能。在这里查看整个计划:

sparseMatrix = ([0,4,5,0],[2,0,4,0],[0,3,3,0],[6,6,0,0])
iList = [3,1,2,4]

def AnalyzeSparseMatrix( sMatrix, iList ):
    orderedArray = [] #The array you want as output
    for i in iList:
        orderedArray += AnalyzeRowWise(sMatrix[i-1])  #Add non-zero selected line from sparse matrix
    return orderedArray #Returns a non-zero list ordered in the selected way by the BFS output list

def AnalyzeRowWise( oldArray ):
    newMatrix = []
    #Code to analize row wise
    for data in oldArray:
        if(data != 0): #Condition
            newMatrix.append(data)
    return newMatrix

#Test program
print (AnalyzeSparseMatrix(sparseMatrix, iList)) #Output: [3,3,4,5,2,4,6,6]

新方法AnalyzeSparseMatrix()接受两个参数,第一个参数是稀疏矩阵,第二个参数是BFS输出列表。该方法返回一个列表,这是所需的列表。因此,您可以将该列表分配给所需的其他列表,例如:

finalOrderedList = AnalyzeSparseMatrix( sparseMatrix, iList )

在上面的代码中查找有关几乎所有代码行的详细信息。

答案 1 :(得分:2)

我认为这就是你想要的:

bfs_output = list of row indexes where 1 is the first/top row of a matrix.
matrix m = some matrix with elements that can be 0 or non-zero
list l = a list composed of non-zero elements chosen from m

m中的元素选择如下:

  1. 选择bfs_output中第一个/下一个值所指示的行r,以m为单位

  2. 从r的第一列开始,选择r

  3. 中的非零元素
  4. 将2中选择的元素附加到l

  5. 重复直到bfs_output

  6. 中不再有行索引

    例如:

                                      0 3 1
    bfs_output = [2 3 1]  &  matrix = 0 2 0    ==> list = [2 4 3 1]
                                      4 0 0
    

    我不确定这是不是你所追求的。但如果是的话,我们可以在选择函数中使用numpy的构建来从numpy数组中选择非零元素,并按照我们想要的顺序选择行。

    from io import StringIO
    import numpy as np
    
    bfs_output = [2,3,1]
    file = StringIO(u"0,3,1\n0,2,0\n4,0,0")
    
    matrix = np.loadtxt(file, delimiter=",")
    
    # we are subtracting 1 from all elements in bfs_output
    # in order to comply with indexes starting from 1
    select_rows = matrix[np.subtract(bfs_output,1)]
    select_rows_1d = np.reshape(select_rows,np.size(select_rows))
    list = select_rows_1d[select_rows_1d != 0]
    
    print(list) # output = [2 4 3 1]