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



我正在尝试根据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开始开始。

重要更新

现在,我通过阅读克里斯蒂安的答案来获得您完全想要的东西。我做出了另一个功能来补充已经给出的功能。在此处查看整个程序:

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 )

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

我假设这就是您想要的:

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. 在m中选择该行,r,由bfs_output中的第一个/下一个值指示

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

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

  5. 重复直到bfs_output中没有更多的行索引

例如:

                                  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,1n0,2,0n4,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]

最新更新