How can I create a const boost matrix?
The following did not work:
const boost::numeric::ublas::matrix<double> arrayM(1, 3) = { {1.0, 2.0, 3.0} };
Usually something akin to:
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();
You might also try something like this (mostly untested):
#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;
}
Same idea, more generic. Also a bit more visual, which can be nice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With