2010-04-02 37 views
4

如何创建常量提升矩阵?如何创建const boost矩阵?

下不工作:

const boost::numeric::ublas::matrix<double> arrayM(1, 3) = { {1.0, 2.0, 3.0} }; 
+0

它不起作用,因为您声明了一个常量矩阵,然后尝试使用可变赋值运算符为其分配值。以下GMan的解决方案将满足您的需求。 – 2010-04-02 22:48:09

+0

我应该清楚我的问题: 有没有一种方法可以用类似的方式创建它,我们创建一个常量数组? 例如: int billy [5] = {16,2,77,40,12071}; – 2010-04-02 22:51:25

回答

8

通常以一个类似于:

typedef boost::numeric::ublas::matrix<double> matrix_type; 

const matrix_type get_matrix(void) 
{ 
    matrix_type result(1, 3); 
    result(0, 0) = 1; 
    result(0, 1) = 2; 
    result(0, 2) = 3; 

    return result; 
} 

const matrix_type arrayM = get_matrix(); 

你也可以尝试这样的事情(主要是未经测试):

#include <boost/numeric/ublas/matrix.hpp> 
#include <boost/numeric/ublas/io.hpp> 

template <typename T, typename L = boost::numeric::ublas::row_major, 
      typename A = boost::numeric::ublas::unbounded_array<T> > 
class matrix_builder 
{ 
public: 
    // types 
    typedef boost::numeric::ublas::matrix<T, L, A> matrix_type; 
    typedef typename matrix_type::size_type size_type; 

    // creation 
    matrix_builder(size_type pRows, size_type pColumns) : 
    mMatrix(pRows, pColumns), 
    mRow(0), 
    mColumn(0) 
    {} 

    matrix_builder& operator()(const T& pValue) 
    { 
     mMatrix(mRow, mColumn) = pValue; 
     if (++mColumn == mMatrix.size2()) 
     { 
      mColumn = 0; 
      mRow++; 
     } 

     return *this; 
    } 

    // access 
    operator const matrix_type&(void) const 
    { 
     return mMatrix; 
    } 

private: 
    // non copyable 
    matrix_builder(const matrix_builder&); 
    matrix_builder& operator=(const matrix_builder&); 

    // members 
    matrix_type mMatrix; 
    size_type mRow; 
    size_type mColumn; 
}; 

typedef boost::numeric::ublas::matrix<double> matrix_type; 

static const matrix_type m1 = matrix_builder<double>(3, 1) 
           (1)(2)(3); 

static const matrix_type m2 = matrix_builder<double>(3, 3) 
           (1)(2)(3) 
           (4)(5)(6) 
           (7)(8)(9); 

int main(void) 
{ 
    std::cout << m1 << std::endl; 
    std::cout << m2 << std::endl; 
} 

相同的想法,更通用。还有一点更直观,可以很好。

+0

尽管这有效,但我会为每个需要创建的常量矩阵类型创建一个函数。 – 2010-04-02 22:48:20

+2

@Venkata:我现在写一个更通用的方法。 – GManNickG 2010-04-02 22:53:07

+0

+1不错的一个GMan! – StackedCrooked 2010-04-02 23:43:42