我有两个 c++ 函数 (foo, goo) 在坐标存储格式中使用稀疏矩阵, 也就是说,矩阵由 3 个数组给出:row_index[nnz]、column_index[nnz]、value[nnz] 其中 nnz 是非零元素的数量。
foo “按行优先顺序”返回稀疏矩阵,例如:
- 1 1 4.000000
- 1 2 4.000000
- 2 1 6.000000
- 2 3 8.000000
- 3 3 10.000000
goo 相反,需要 vector 按“按列优先顺序”排序,即:
- 1 1 4.000000
- 2 1 6.000000//这个改了
- 1 2 4.000000//这个改了
- 2 3 8.000000
- 3 3 10.000000
我怎样才能以最有效的方式进行这种转换?
附加信息: goo 还支持压缩列格式。
最佳答案
如果您可以通过执行来控制数据结构,那么一种干净、高效的方法是将格式存储为结构数组,然后将 w.r.t 排序到相关列,例如
typedef std::tuple<size_t,size_t,double> elem_t;
// std::get<0>(storage[i]) is the row index of the i-th non-zero
// std::get<1>(storage[i]) is the col index of the i-th non-zero
// std::get<2>(storage[i]) is the value of the i-th non-zero
std::vector<elem_t> storage;
// this sort can be parallel
std::sort(storage.begin(),storage.end(),[](const elem_t& L, const elem_t& R){return std::get<1>(L)<std::get<1>(R);});
如果没有,可以写一个仿函数,按照列做索引排序,然后再置换。这当然会更加困惑,并且会产生内存开销。
关于c++ - 稀疏矩阵坐标存储格式: convert from row-major to column-major,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27177664/