c++ - 稀疏矩阵坐标存储格式: convert from row-major to column-major

标签 c++ matrix

我有两个 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/

相关文章:

从 R 中的矩阵中删除行名列表

c++ - 为什么 lambda 的大小为 1 个字节?

c++ - 使用 clang 对 std::atomic 函数的调用不明确

c++ - 引用成员抽象类的Boost序列化

c++ - 如何通过绑定(bind)另一个成员函数的参数来创建 C++ 成员函数?

c - 从 C 中的矩阵中删除分号

C++ - std::map.insert() 段错误

C 使用指针从矩阵中提取数组

arrays - 从列中分块对角矩阵

math - 正确的OpenGL矩阵格式?