c++ - boost 压缩矩阵基础知识

标签 c++ optimization boost matrix sparse-matrix

我对 boost::compressed_matrix 的工作原理感到困惑。假设我这样声明 compressed_matrix:

boost::numeric::ublas::compressed_matrix<double> T(1000, 1000, 3*1000);

这为 1000x1000 矩阵中的 3*1000 个元素分配了空间。现在我如何给它指定非零元素的位置?何时以及如何设置非零元素?每次我在矩阵中分配一个元素时,例如B(4,4)=4,它会将那个元素标记为非零?

如果可能的话,如果您能通过示例帮助我了解这一点,我将不胜感激。对内部实现有一些了解会很棒。我想确保我不会通过猜测编写出次优的程序。

谢谢!

最佳答案

压缩矩阵有一个底层线性容器(默认情况下是unbounded_array,但如果你愿意,你可以把它变成bounded_arraystd::vector ),其中包含矩阵的所有非零元素,按行优先(默认)顺序排列。这意味着无论何时将新的非零元素写入压缩矩阵,它都会被插入到底层数组中。如果您没有按(行优先)顺序填充矩阵,则每个插入都将为 O(n)。当您更改现有的非零元素时,它只会在底层数组中发生更改。

下面是一个简单的测试,看看底层结构是什么样的:

#include <boost/numeric/ublas/matrix_sparse.hpp>
#include <boost/numeric/ublas/storage.hpp>
namespace ublas = boost::numeric::ublas;
void show_array(const ublas::unbounded_array<double>& a)
{
    for(size_t i=0; i<a.size(); ++i)
            std::cout << a[i] << ' ';
    std::cout << '\n';
}
int main()
{
    ublas::compressed_matrix<double> m (10, 10, 3 * 10);
    m(0, 5) = 1; // underlying array is {1, 0, 0, 0, ...}
    show_array(m.value_data());
    m(0, 6) = 2; // underlying array is {1, 2, 0, 0, ...}
    show_array(m.value_data());
    m(0, 4) = 3;  // underlying array is {3, 1, 2, 0, ...}
    show_array(m.value_data());
    m(0, 4) = 7;  // underlying array is {7, 1, 2, 0, ...}
    show_array(m.value_data());
}

关于c++ - boost 压缩矩阵基础知识,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3765026/

相关文章:

c++ - 在我的类 .cpp 文件 : "error: class ' Test' does not have any field named 'counter' "中类头和使用构造函数

c++ - 我应该如何避免 SQL 超时?

python - 在 Python 中加载 C 共享库期间出现 OSError( undefined symbol :checkedCalloc)

performance - 优化重复的 matlab 代码

c++ - 当c++模板定义带有=时是什么意思

c++ - boost::asio::deadline_timer cancel() 方法未调用计时器处理程序

c++ - 在 C++ 应用程序中嵌入 Ruby 解释器

performance - 创建 Lua 函数的本地副本有任何性能值(value)吗?

c - 这个简单游戏的高效算法

c++ - 是什么阻止了 Boost.Format 表单使用我的可选 int 流运算符重载?