Palash Kumar
Palash Kumar

Reputation: 429

How to convert STL vector of vector to armadillo mat?

Given vector<vector<double > > A_STL, I want it to get converted into arma::mat A.

Upvotes: 7

Views: 2935

Answers (2)

zanzu
zanzu

Reputation: 65

The following lines should do the job:

template<typename T>
arma::Mat<T> convertNestedStdVectorToArmadilloMatrix(const std::vector<std::vector<T>> &V) {
    arma::Mat<T> A(V.size(), V[0].size());

    for (unsigned_t i{}; i < V.size(); ++i) {
        A.row(i) = arma::conv_to< arma::Row<T> >::from(V[i]);
    }
    return A;
}

Test with:

std::vector<std::vector<float_type>> vec = {{1.0, 2.0, 3.0}, {4.0, 5.0, 6.0}};
arma::Mat<float_type> mat = convertNestedStdVectorToArmadilloMatrix(vec);

Upvotes: 0

coincoin
coincoin

Reputation: 4685

One simple way would be to flatten your vector of vector matrix into one dimensional vector. And you can therefore use your mat(std::vector) constructor.

Code example (not tested) :

// Flatten your A_STL into A_flat
std::vector<double> A_flat;
for (auto vec : A_STL) {
  for (auto el : vec) {
    A_flat.push_back(el);
  }
}
// Create your Armadillo matrix A
mat A(A_flat);

Beware of how you order your vector of vector. A_flat should be column major.

Upvotes: 6

Related Questions