增强中的矩阵求逆

时间:2013-06-21 17:00:06

标签: c++ boost

我正在尝试使用boost进行简单的矩阵求逆操作。但是我 我收到了一个错误。 基本上我想找到的是inversted_matrix = 逆(trans(矩阵)*矩阵) 但是我收到了一个错误

Check failed in file boost_1_53_0/boost/numeric/ublas/lu.hpp at line 299: 
detail::expression_type_check (prod (triangular_adaptor<const_matrix_type, 
upper> (m), e), cm2) 
terminate called after throwing an instance of 
'boost::numeric::ublas::internal_logic' 
  what(): internal logic 
Aborted (core dumped) 

我的尝试:

#include <boost/numeric/ublas/matrix.hpp> 
#include <boost/numeric/ublas/vector.hpp> 
#include <boost/numeric/ublas/io.hpp> 
#include <boost/numeric/ublas/vector_proxy.hpp> 
#include <boost/numeric/ublas/matrix.hpp> 
#include <boost/numeric/ublas/triangular.hpp> 
#include <boost/numeric/ublas/lu.hpp> 

namespace ublas = boost::numeric::ublas; 
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; 
    // 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; 
}

int main(){ 
    using namespace boost::numeric::ublas; 
    matrix<double> m(4,5); 
    vector<double> v(4); 
    vector<double> thetas; 
    m(0,0) = 1; m(0,1) = 2104; m(0,2) = 5; m(0,3) = 1;m(0,4) = 45; 
    m(1,0) = 1; m(1,1) = 1416; m(1,2) = 3; m(1,3) = 2;m(1,4) = 40; 
    m(2,0) = 1; m(2,1) = 1534; m(2,2) = 3; m(2,3) = 2;m(2,4) = 30; 
    m(3,0) = 1; m(3,1) = 852; m(3,2) = 2; m(3,3) = 1;m(3,4) = 36; 
    std::cout<<m<<std::endl; 
    matrix<double> product = prod(trans(m), m); 
    std::cout<<product<<std::endl; 
    matrix<double> inversion(5,5); 
    bool inverted; 
    inverted = InvertMatrix(product, inversion); 
    std::cout << inversion << std::endl; 
} 

2 个答案:

答案 0 :(得分:6)

Boost Ublas进行了运行时检查,以确保数值稳定性。 如果您查看错误的来源,您可以看到它尝试确保错误 U*X = B, X = U^-1*B, U*X = B(或那样的smth)在某些epsilon中是coorect。如果你在数字上有太多的偏差,这可能不会成立。

您可以通过-DBOOST_UBLAS_NDEBUG禁用检查,也可以使用BOOST_UBLAS_TYPE_CHECK_EPSILON, BOOST_UBLAS_TYPE_CHECK_MIN旋转。

答案 1 :(得分:3)

由于m只有4行,prod(trans(m), m)不能有高于4的等级,并且由于乘积是5x5矩阵,它必须是单数(即它具有行列式0)并计算奇异矩阵的逆类似于除以0.将独立行添加到m以解决此奇点问题。