Skip to content

Instantly share code, notes, and snippets.

@SolemnJoker
Last active November 7, 2020 13:51
Show Gist options
  • Save SolemnJoker/4f041153d04cce3586c264f706bd532d to your computer and use it in GitHub Desktop.
Save SolemnJoker/4f041153d04cce3586c264f706bd532d to your computer and use it in GitHub Desktop.
[eigen库] #c++

一.变量操作

1.定义变量

Eigen::MatrixXd m1(row,col); /row*col double
Eigen::Matrix3d m2;//3*3 double
Eigen::Matrix3Xd m3(row);//row*3 double
Eigen::Matrix<double,row,col,Eigen::RowMajor> m4; //
Eigen::Matrix<double,row,Eigen::Dynamic,Eigen::RowMajor> m5(col); // row*col 

Eigen::Vector3d v1;
Eigen::VectorXd v2;

2.访问

//index
m1(r,c) = value;
std::cout<<m1(3,c)<<std::endl;
vec[i] = value;

//<<
Eigen::MatrixXd m2(3,2);
m2<<1,2,3,4,5,6;
Eigen::Vector3d v2;
v2<<1,2,3;

//row
Eigen::Matrix3Xd m(row);//row*3 double
Eigen::Vector3d v;
Eigen::Vector3d res = m.row(i)  + v;

数学运算

//转置
Eigen::MatrixXd m1(3,2);
Eigen::MatrixXd m2(2,3);
Eigen::Vector3d v;
auto mt = m1.transpose();
auto vt = v.transpose();

//点乘,Eigen区分左乘右乘以及行列向量
auto res1 = m1*m2;
auto res2 = v.transpose()*m1;
auto res3 = m1*v;//实际上这里v会被当成二维向量与m1相乘,也就是说eigen矩阵和向量相乘时,向量长度超过对应的矩阵的行或列,会被截断并继续计算,而不是报错终止.

二.注意事项

延迟计算

Eigen会有延迟计算,当使用auto自动推导计算结果时,不会执行真正的计算,保存结果的变量只是记录了运算操作,在后面才会实际计算.

Eigen::MatrixXd m1(3,2);
Eigen::MatrixXd m2(2,3);
Eigen::MatrixXd m3(2,3);
auto res1 = m1*m2;//不会执行计算
Eigen::MatrixXd res2 = m1*m2;//执行计算
Eigen::MatrixXd res3 = res1*m3;//执行m1*m2,res1*m3计算

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment