8
votes

This question was asked in haste. The error in my original program, was not the typo in the code that is displayed here. The error was that in my program v was not getting populated due to some conditions.

The more useful takeaway from this thread is the demonstration of copying a std::vector to all rows or columns of an Eigen Matrix, in the accepted answer.


I want to copy vectors into the columns of a matrix, like the following:

#include <Eigen/Dense>
#include <vector>
#include <iostream>

int main() {
 int m = 10;

 std::vector<Eigen::VectorXd> v(m);
 Eigen::MatrixXd S(m,m);

 for (int i = 0; i != m; ++i) {
  v[i].resize(m);

  for (int j = 0; j != m; ++j) {
   v[i](j) = rand() % m;
  }

  //S.cols(i) = v[i]; //needed something like this
 }

 return 0;
}

S is of type Eigen::MatrixXd and dimension mxm. v is a std::vector of Eigen::VectorXd, where each Eigen::VectorXd is of size m and there are m of them in v.

1

1 Answers

7
votes

Regarding the original question, you need to wrap the std::vector with an Eigen::Map. You could/should also make the operation a one-liner.

The reworded question is reduced to a typo. S.cols(i) should be S.col(i).

int main()
{
    size_t sz = 6;
    Eigen::MatrixXd S(sz, sz);
    std::vector<double> v(sz);
    std::vector<Eigen::VectorXd> vv(sz);
    for(int i = 0; i < sz; i++)
    {
        v[i] = i*2;
        vv[i] = Eigen::VectorXd::LinSpaced(sz, (i+sz), (i+sz)*2);
    }

    for (int i = 0; i != sz; ++i)
        S.col(i) = vv[i];
    std::cout << S << "\n\n";

    S.rowwise() = Eigen::Map<Eigen::RowVectorXd>(v.data(), sz);
    std::cout << S << "\n\n";

    S.colwise() = Eigen::Map<Eigen::VectorXd>(v.data(), sz);
    std::cout << S << "\n\n";

    return 0;
}

which would output

6 7 8 9 10 11
7.2 8.4 9.6 10.8 12 13.2
8.4 9.8 11.2 12.6 14 15.4
9.6 11.2 12.8 14.4 16 17.6
10.8 12.6 14.4 16.2 18 19.8
12 14 16 18 20 22

0 2 4 6 8 10
0 2 4 6 8 10
0 2 4 6 8 10
0 2 4 6 8 10
0 2 4 6 8 10
0 2 4 6 8 10

0 0 0 0 0 0
2 2 2 2 2 2
4 4 4 4 4 4
6 6 6 6 6 6
8 8 8 8 8 8
10 10 10 10 10 10