简体   繁体   English

将向量分配给Eigen中的矩阵列

[英]Assigning a vector to a matrix column in Eigen

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. 错误是我的程序v由于某些条件而没有填充。

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. 这个主题的更有用的内容是在接受的答案中演示将std :: vector复制到Eigen Matrix的所有行或列。


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. S的类型为Eigen :: MatrixXd,维度为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. v是Eigen :: VectorXd的std :: vector,其中每个Eigen :: VectorXd的大小为m,并且v中有m个。

Regarding the original question, you need to wrap the std::vector with an Eigen::Map . 关于原始问题,您需要使用Eigen::Map包装std::vector 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) . S.cols(i)应为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 6 7 8 9 10 11
7.2 8.4 9.6 10.8 12 13.2 7.2 8.4 9.6 10.8 12 13.2
8.4 9.8 11.2 12.6 14 15.4 8.4 9.8 11.2 12.6 14 15.4
9.6 11.2 12.8 14.4 16 17.6 9.6 11.2 12.8 14.4 16 17.6
10.8 12.6 14.4 16.2 18 19.8 10.8 12.6 14.4 16.2 18 19.8
12 14 16 18 20 22 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 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 0 0 0 0 0 0
2 2 2 2 2 2 2 2 2 2 2 2
4 4 4 4 4 4 4 4 4 4 4 4
6 6 6 6 6 6 6 6 6 6 6 6
8 8 8 8 8 8 8 8 8 8 8 8
10 10 10 10 10 10 10 10 10 10 10 10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM