如何创建const boost矩阵?
以下不起作用:
const boost::numeric::ublas::matrix<double> arrayM(1, 3) = { {1.0, 2.0, 3.0} };
答案 0 :(得分: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;
}
同样的想法,更通用。还有点视觉,这可能很好。