我正在尝试使用 boost c++ 库计算行列式。我找到了下面复制的函数 InvertMatrix() 的代码。每次我计算这个逆时,我也想要行列式。通过从 LU 分解中乘以 U 矩阵的对角线,我很清楚如何计算。有一个问题,我能够正确计算行列式,除了符号。根据旋转我得到的符号不正确的一半时间。有没有人对如何每次都获得正确的标志有建议?提前致谢。
template<class T>
bool InvertMatrix(const ublas::matrix<T>& input, ublas::matrix<T>& inverse)
{
using namespace boost::numeric::ublas;
typedef permutation_matrix<std::size_t> pmatrix;
// create a working copy of the input
matrix<T> A(input);
// create a permutation matrix for the LU-factorization
pmatrix pm(A.size1());
// perform LU-factorization
int res = lu_factorize(A,pm);
if( res != 0 ) return false;
在这里,我插入了计算行列式的最佳方法。
T determinant = 1;
for(int i = 0; i < A.size1(); i++)
{
determinant *= A(i,i);
}
结束我的部分代码。
// create identity matrix of "inverse"
inverse.assign(ublas::identity_matrix<T>(A.size1()));
// backsubstitute to get the inverse
lu_substitute(A, pm, inverse);
return true;
}