简体   繁体   中英

Eigen - reshape a vector to matrix

I am trying to reshape a vector to a matrix, but getting the following error

unsigned int Nx     = 8;
unsigned int Ny     = 7;
Eigen::VectorXi G_temp = Eigen::VectorXi::LinSpaced((Nx + 2) * (Ny + 2),0,(Nx + 2) * (Ny + 2)-1);
Eigen::MatrixXd G = Eigen::Map<Eigen::MatrixXd>(G_temp.data(),Nx+2, Ny+2); // error: no matching constructor for initialization of 'Eigen::Map<Eigen::MatrixXd>'

I followed what is written here , but I do not understand the way I am doing wrong.

There is no implicit conversion from integer-valued to double-valued expressions in Eigen. Either just use VectorXd for G_temp (and the LinSpaced expression):

Eigen::VectorXd G_temp = Eigen::VectorXd::LinSpaced((Nx + 2) * (Ny + 2),0,(Nx + 2) * (Ny + 2)-1);

Or use a MatrixXi -Map and .cast<double>() the result before assigning it to G .

Eigen::MatrixXd G = Eigen::Map<Eigen::MatrixXi>(G_temp.data(),Nx+2, Ny+2).cast<double>();

To avoid any temporary, you can also allocate a MatrixXd and directly assign the proper values inside:

Eigen::MatrixXd G(Nx+2, Ny+2); // allocate matrix
// set values in-place:
Eigen::VectorXd::Map(G.data(), (Nx + 2) * (Ny + 2)).setLinSpaced(0,(Nx + 2) * (Ny + 2)-1);

Or with the master/3.4 branch:

G.reshaped().setLinSpaced(0,(Nx + 2) * (Ny + 2)-1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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