如您所知,我们可以使用压缩行存储(CRS)(或者压缩稀疏行(CSR))来编写稀疏矩阵。
假设A是一个m×n的矩阵,则其转置A'是一个n×m的矩阵,对于所有0 <= i < n和0 <= j < m,A'(i; j) = A(j; i)。
我需要编写CRS表示法下矩阵转置的算法。我该如何解决这个问题?
我需要编写CRS表示法下矩阵转置的算法。我该如何解决这个问题?
struct CRSMatrix
{
int n; // number of rows
int m; // number of columns
int nz; // number of non-zero elements
std::vector<double> val; // non-zero elements
std::vector<int> colIndex; // column indices
std::vector<int> rowPtr; // row ptr
};
这个函数执行它:
CRSMatrix sparse_transpose(const CRSMatrix& input) {
CRSMatrix res{
input.m,
input.n,
input.nz,
std::vector<double>(input.nz, 0.0),
std::vector<int>(input.nz, 0),
std::vector<int>(input.m + 2, 0) // one extra
};
// count per column
for (int i = 0; i < input.nz; ++i) {
++res.rowPtr[input.colIndex[i] + 2];
}
// from count per column generate new rowPtr (but shifted)
for (int i = 2; i < res.rowPtr.size(); ++i) {
// create incremental sum
res.rowPtr[i] += res.rowPtr[i - 1];
}
// perform the main part
for (int i = 0; i < input.n; ++i) {
for (int j = input.rowPtr[i]; j < input.rowPtr[i + 1]; ++j) {
// calculate index to transposed matrix at which we should place current element, and at the same time build final rowPtr
const int new_index = res.rowPtr[input.colIndex[j] + 1]++;
res.val[new_index] = input.val[j];
res.colIndex[new_index] = i;
}
}
res.rowPtr.pop_back(); // pop that one extra
return res;
}
res.rowPtr
是什么的人来说:你需要一个数据结构来回答一个简单的查询问题“在这个元素之前有多少个元素被放置了?”,所以如果你仔细观察res.rowPtr
,你会发现对于colIndex[i]
(转置后的行索引),答案被放置在colIndex[I]+1
中。而res.rowPtr.pop_back();
可以在主循环之前出现。 - undefined