gpt4 book ai didi

c++ - 具有可参数化 "zero"的稀疏矩阵类

转载 作者:IT老高 更新时间:2023-10-28 23:21:34 24 4
gpt4 key购买 nike

我正在对日志域中的浮点稀疏矩阵进行一些计算,因此“空”条目实际上是 -Inf(使用 -FLT_MAX)。我现在正在使用一个自定义稀疏矩阵类,但我很想换一个现成的替代品。

这是用 C++ 编写的。我倾向于查看 Eigen 和 Boost uBlas 中的压缩列矩阵。但是,不清楚是否支持“零”的自定义值(可能由模板参数提供)。有人有什么建议吗?

澄清:

我想要的是:对于之前没有“设置”的任何单元格 (i,j),我希望 mat[i,j] 返回 -Inf ...所以这可能更好地描述为稀疏矩阵的“空”条目的“默认”值。

我正在使用它来执行 HMM 递归(维特比,求和积),并将概率保存在日志域中以避免下溢。

我没有做任何矩阵运算......我只是在填写动态规划表,本质上。我想使用稀疏矩阵类,因为我只填充矩阵的一个带,并且我希望有效地使用内存。压缩带矩阵将提供良好的性能,因为我正在“按顺序”填充矩阵。

最佳答案

这样的事情怎么样?

class compressed_matrix_nonzero_default : public boost::numeric::ublas::compressed_matrix<double>
{
double def;
public:
compressed_matrix_nonzero_default( int s1, int s2 )
: boost::numeric::ublas::compressed_matrix<double>(s1,s2)
, def(0)
{

}
void setDefault( double d ) { def = d; }
double value( int i, int j )
{
typedef boost::numeric::ublas::compressed_matrix<double>::iterator1 it1_t;
typedef boost::numeric::ublas::compressed_matrix<double>::iterator2 it2_t;
for (it1_t it1 = begin1(); it1 != end1(); it1++)
{
if( it1.index1() < i )
continue;
if( it1.index1() > i ) {
return def;
}
for (it2_t it2 = it1.begin(); it2 != it1.end(); it2++)
{
if( it2.index2() < j )
continue;
if( it2.index2() == j )
return *it2;
if( it2.index2() > j )
return def;
}


}
return def;
}

};

用法

compressed_matrix_nonzero_default MNZ(3,3);
MNZ.setDefault(-100);
MNZ (1,1) = 45;

for( int i = 0; i < 3; i++ ) {
for( int j = 0; j < 3; j++ ) {
std::cout << MNZ.value(i,j) << ",";
}
std::cout << "\n";
}

关于c++ - 具有可参数化 "zero"的稀疏矩阵类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7258198/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com