我有一个程序正在读取以下格式的数据:
Row Column Value
1 1 4
1 3 5
2 1 6
...
其中前两列指的是矩阵的索引,值列包含存储在矩阵中该(行,列)坐标处的值。
如果我要实际构造一个二维数组来表示矩阵,它会非常大,因为我的输入数据非常稀疏。相反,我想构建一个稀疏矩阵表示,使我能够查找对应于(行,列)对的值,如果不存在则返回 0。
boost 似乎有办法做到这一点,但我找不到足够的文档来真正理解如何使用它。
我已经深入阅读了这些内容,但我仍然不确定如何继续:
http://www.guwi17.de/ublas/doc/html/ex__fill1_8cpp-source.html http://www.boost.org/doc/libs/1_39_0/libs/numeric/ublas/doc/matrix_sparse.htm
我是 C++ 新手,所以不确定如何使用 boost 从我的输入数据创建稀疏矩阵(假设我已经读入了它)。我也没有找到如何使用 boost 稀疏矩阵实际返回与(行,列)对相关的值。任何人都可以指出一些基本示例,或者解释我如何做到这一点吗?
感谢您提供的任何帮助。
最佳答案
boost 中有几种稀疏矩阵实现:mapped_matrix
(由关联容器支持,例如 std::map
)、compressed_matrix
和 coordinate_matrix
(由可调整大小的数组支持)。它们的用法都是一样的。
这里是压缩矩阵的一些基础知识:
#include <iostream>
#include <sstream>
#include <boost/numeric/ublas/matrix_sparse.hpp>
namespace ublas = boost::numeric::ublas;
int main()
{
ublas::compressed_matrix<int> m(10, 10); // 10x10 compressed matrix
// replace by ifstream in("filename") in real code
std::istringstream in("1 1 4\n"
"1 3 5\n"
"2 1 6\n");
// read from stream
int val;
for(size_t r,c; in >> r >> c >> val; )
m(r,c) = val;
// print out
for(size_t i = 0; i < m.size1(); ++i)
{
for(size_t j = 0; j < m.size2(); ++j)
std::cout << m(i,j) << ' ';
std::cout << '\n';
}
// info on the storage
std::cout << "Non-zeroes: " << m.nnz() << '\n'
<< "Allocated storage for " << m.nnz_capacity() << '\n';
}
关于c++ - 使用 boost 来构建和访问稀疏矩阵中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15488588/