给MTL库添加求行列式值

在使用MTL库的时候,发现mtl库没有求行列式的值的函数,google了一把,找到下面的网页

How to Find Determinant of nxn matrix?

参考里面的说明,给mtl加上了,求行列式值的功能。

新建一个C++的头文件,名称随便取,在里面输入下面的代码:

   
#include <mtl/matrix.h> #include <mtl/mtl.h> #include <mtl/dense1D.h> #include <mtl/utils.h> #include <mtl/lu.h> namespace mtl { /*!This function calculates the determinant of a matrix */ template<class MatrixType> double lu_det(const MatrixType& _Matrix) { int size = _Matrix.nrows(); MatrixType LU(size,size); dense1D<int> pvector(size); copy(_Matrix, LU); lu_factor(LU, pvector); // For every permutation of rows the product of diagonal elements has to be multyplied by -1 int sign = 1; for (int i = 0 ; i < size ; ++i){ if ( pvector[i] != i+1 ) sign *= -1; } typename MatrixType::iterator iter; iter = LU.begin(); double det = 1.0; unsigned ind = 0; for ( iter = LU.begin(); iter != LU.end(); ++iter ){ ind = iter.index(); det *= LU(ind, ind); } det *= sign; return det; } }

然后在自己的程序中,定义一个mtl的矩阵,就可以直接使用lu_det来计算了,需要注意的是,输入的矩阵行列必须相等。

 

 

你可能感兴趣的:(c,function,Google,iterator,Matrix,permutation)