views:

229

answers:

4

How can I define a array of boost matrices as a member variable?

None of the following worked.

boost::numeric::ublas::matrix<double> arrayM(1, 3)[arraySize];
boost::numeric::ublas::matrix<double>(1, 3) arrayM[arraySize];
boost::numeric::ublas::matrix<double> arrayM[arraySize](1, 3);

Thanks, Ravi.

+3  A: 

The size you initialize it with has nothing to do with the type. Therefore:

// this makes things easier!
typedef boost::numeric::ublas::matrix<double> matrix_type;

// this is the type (no initialization)
matrix_type arrayM[arraySize];

The problem comes with initializing the array. You can't do this:

TheClass::TheClass() :
arrayM(1, 3) // nope
{}

Instead, you have to let them default-construct, then resize them all:

TheClass::TheClass()
{
    std::fill(arrayM, arrayM + arraySize, matrix_type(1, 3));
}

Since you're using boost, consider using boost::array, since it gives a nicer syntax:

typedef boost::numeric::ublas::matrix<double> matrix_type;
typedef boost::array<matrix_type, arraySize> matrix_array;

matrix_array arrayM; // ah

TheClass::TheClass()
{
    arrayM.assign(matrix_type(1, 3));
}
GMan
+2  A: 

Array initialization use the default constructor. You can use a vector instead:

class MyClass {
    std::vector<boost::numeric::ublas::matrix<double>> vectorM;
public:
    MyClass() : vectorM(10, boost::numeric::ublas::matrix<double>(5,7)) {
    }
};
Alexandre Jasmin
+1  A: 

How about:

// Assume: arraySize is a constant
// Assume: #include <boost/tr1/array.hpp>

typedef boost::numeric::ublas::matrix<double> doubleMatrixT;
std::tr1::array<doubleMatrixT, arraySize> arrayM;
arrayM.assign(doubleMatrixT(1, 3));

The std::tr1::array template is a (very) thin wrapper around basic arrays that offers convenience functions. For example, here I’ve used assign(), which fills the entire array with a single value.

Nate
+3  A: 

It's not clear to me exactly what you're trying to initialize, but taking a guess (array with arraySize entries; each entry in the array is initialized with (1, 3)), I came up with this, which compiles....

const size_t arraySize = 3;
boost::numeric::ublas::matrix<double> arrayM[arraySize] = 
{
    boost::numeric::ublas::matrix<double>(1, 3),
    boost::numeric::ublas::matrix<double>(1, 3),
    boost::numeric::ublas::matrix<double>(1, 3)
};
jwismar
Wow. You posted the exact same thing as me 2 seconds before me. I'm impressed. Here's a good link to explain it and I'll delete my answer: http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.5
Brendan Long