How to convert STL vector of vector to armadillo mat?
Asked Answered
M

2

7

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

Monotheism answered 2/6, 2015 at 9:51 Comment(3)
What did you try ? What didn't work ? And why are you insisting on garbling your formatting ?Spittoon
Because A_STL is actually a vector of vectors, not just a vector of doubleMonotheism
Yep, saw that and didn't change it. But without proper formatting, your template instantiations are getting stripped as malformed html tags.Spittoon
W
6

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.

Wiedmann answered 2/6, 2015 at 10:0 Comment(2)
how is the width and height dimensions determined(specified) in the created arma::mat?Beitch
is it possible to provide it in the constructor or it should be applied using the reshape method?Beitch
R
0

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);
Ribonuclease answered 31/5, 2023 at 9:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.