Search code examples
c++boostmatrixublas

Initializing boost matrix with a std::vector or array


I have a method that takes a std::vector as one of its parameters. Is there a way I can initialize a matrix by assigning the std::vector to the matrix? Here's what I tried to do below. Does anyone know how i can achieve assigning the vector (or even a pointer of doubles) to the matrix? Thanks in advance. Mike

void Foo(std::vector v)
{
    matrix<double> m(m, n, v);
    // work with matrix...
}

Solution

  • According to the boost matrix documentation, there are 3 constructors for the matrix class: empty, copy, and one taking two size_types for the number of rows and columns. Since boost doesn't define it (probably because there are many ways to do it and not every class is gong to define a conversion into every other class) you are going to need to define the conversion.

    Here's an approach that I would use, but since there are multiple ways to do this and the question doesn't specify how you want this done you may find a different approach more applicable to your situation.

    void Foo(const std::vector<double> & v) {
       size_t m = ... // you need to specify
       size_t n = ... // you need to specify
    
       if(v.size() < m * n)   { // the vector size has to be bigger or equal than m * n
          // handle this situation
       }
    
       matrix<double> mat(m, n);
       for(size_t i=0; i<mat.size1(); i++) {
          for(size_t j=0; j<mat.size2(); j++) {
             mat(i,j) = v[i+j*mat.size1()];
          }
       }
    }
    

    A couple of notes about your provided code: std::vector needs a templated argument and you are declaring m as a matrix and an input argument to it's constructor.