Initialization of the gain matrix using std :: vector or an array

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

void Foo(std::vector v)
{
    matrix<double> m(m, n, v);
    // work with matrix...
}
+5
source share
3 answers

3 : , size_types . boost (, , , - gong ), .

, , , , , , .

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()];
      }
   }
}

: std::vector , m .

+3

, :

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

namespace ublas = boost::numeric::ublas;

template <typename T, typename F=ublas::row_major>
ublas::matrix<T, F> makeMatrix(std::size_t m, std::size_t n, const std::vector<T> & v)
{
    if(m*n!=v.size()) {
        ; // Handle this case
    }
    ublas::unbounded_array<T> storage(m*n);
    std::copy(v.begin(), v.end(), storage.begin());
    return ublas::matrix<T>(m, n, storage);
}

int main () {;
    std::vector<double> vec {1, 2, 3, 4, 5, 6};
    ublas::matrix<double> mm = makeMatrix(3,2,vec);
    std::cout << mm << std::endl;
}
+3

A more convenient way is this:

matrix<double> m(m*n);
std::copy(v.begin(), v.end(), m.data().begin());
+1
source

All Articles