使用链表转换稀疏矩阵(遍历问题)

Transposing a sparse matrix using linked lists (Traversal problems)

本文关键字:遍历 问题 链表 转换      更新时间:2023-10-16

我正试图在c++中转置一个稀疏矩阵。我正在努力遍历新的转置矩阵。我想输入从矩阵的第一行到新矩阵的第一列的所有内容。

每一行都有数字应该在其中的列索引和数字本身。

输入:

colInd num

输入:

1 1 2 2 3 3

1 4 2 5 3 6

1 7 2 8 3 9

输出:

1 1 2 4 3 7

1 2 5 3 8

1 3 2 6 3 9

如何使列表遍历第一列,插入第一个元素,然后返回顶部,插入第二列。如果这是两个很难遵循的问题,请道歉。但我所想帮助的是在正确的时间将转置矩阵遍历到正确的位置,在正确的位置插入一个nz(非零)对象。

这是我的代码

list<singleRow> tran;
//Finshed reading so transpose
for (int i = 0; i < rows.size(); i++){ // Initialize transposed matrix
    singleRow trow;
    tran.push_back(trow);
}
list<singleRow>::const_iterator rit;
list<singleRow>::const_iterator trowit; 
int rowind;
for (rit = rows.begin(), rowind = 1; rit != rows.end(); rit++, rowind++){//rit = row iterator
    singleRow row = *rit;
    singleRow::const_iterator nzit;
    trowit = tran.begin(); //Start at the beginning of the list of rows
    trow = *trowit;
    for (nzit = row.begin(); nzit != row.end(); nzit++){//nzit = non zero iterator
            int col = nzit->getCol();
            double val = nzit->getVal();
            trow.push_back(nz(rowind,val)); //How do I attach this to tran so that it goes in the right place?
            trowit++;
    }
}

您对矩阵的表示效率低下:它没有使用矩阵稀疏的事实。我这么说是因为它包括矩阵的所有行,即使它们中的大多数是零(空),就像稀疏矩阵通常发生的那样。

你的代表也很难共事。因此,我建议先转换表示(到一个规则的2-D数组),转换矩阵,然后再转换回来。

(编辑时间:)或者,您可以更改表示,例如,如下所示:

输入:rowInd colInd num

1 1 1
1 2 2
1 2 3
2 1 4
2 2 5
2 3 6
3 1 7
3 2 8
3 3 9

输出:

1 1 1
2 1 2
3 1 3
1 2 4
2 2 5
3 2 6
1 3 7
2 3 8
3 3 9

代码应该是这样的:

struct singleElement {int row, col; double val;};
list<singleElement> matrix_input, matrix_output;
...
// Read input matrix from file or some such
list<singleElement>::const_iterator i;
for (i = matrix_input.begin(); i != matrix_input.end(); ++i)
{
    singleElement e = *i;
    std::swap(e.row, e.col);
    matrix_output.push_back(e);
}

稀疏矩阵的列表表示的选择不适合换位。有时,在考虑算法和数据结构时,最好的做法是承担将数据结构转换为更适合算法的数据结构的风险,而不是破坏算法以使用错误的数据结构。

在这种情况下,例如,你可以将矩阵读取到坐标列表表示中,这将非常容易转换,然后写入你喜欢的任何表示中。如果空间是一个挑战,那么您可能需要逐个块地执行此操作,在目标表示中按1分配新列,并在执行过程中释放旧表示中的列。