Eigen 学习之块操作

  Eigen 为 Matrix 、Array 和  Vector提供了块操作方法。块区域可以被用作 左值 和 右值。在Eigen中最常用的块操作函数是 .block() 。

block() 方法的定义如下:

  block of size (p,q) ,starting at (i,j)。matrix.block(i,j,p,q);     matrix.block<p,q>(i,j);

上述两种形式都可以被用在固定大小和动态大小的矩阵中。

  举例如下:

  

 1 #include <iostream>
 2 #include <eigen3/Eigen/Dense>
 3 
 4 using namespace Eigen;
 5 using namespace std;
 6 
 7 int main(int argc ,char** argv)
 8 {
 9     MatrixXf m(4,4);
10     m << 1,2,3,4,
11          5,6,7,8,
12          9,10,11,12,
13          13,14,15,16;
14     cout<<"Block in the middle"<<endl;
15     cout<<m.block<2,2>(1,1)<<endl<<endl;
16     for(int i = 1; i <= 3; ++i)
17     {
18         cout<<"Block of size "<<i<<" x "<<i<<endl;
19         cout<<m.block(0,0,i,i)<<endl<<endl;
20     }
21     return 0;
22 }

  

  block也可以被用作左值,即block可以进行赋值操作。

  举例如下:

  

 1 #include <iostream>
 2 #include <eigen3/Eigen/Dense>
 3 
 4 using namespace Eigen;
 5 using namespace std;
 6 
 7 int main(int argc ,char** argv)
 8 {
 9     Array22f m;
10     m << 1,2,
11          3,4;
12 
13     Array44f a = Array44f::Constant(0.6);
14     cout<<"Here is the array a"<<endl<<a<<endl<<endl;
15     a.block<2,2>(1,1) = m;
16     cout<<"Here is now a with m copoed into its central 2x2 block"<<endl<<a<<endl<<endl;
17     a.block(0,0,2,3) = a.block(2,1,2,3);
18     cout<<"Here is now a with bottom-right 2x3 copied into top-left 2x3 block:"<<endl<<a<<endl<<endl;
19     return 0;
20 }

  运行结果如下:

  

 

  特殊情况下的块操作,比如取整行或者整列,取上面的若干行或者底部的若干行。

  取 整行和整列的操作如下:

    matrix.row(i);

              matrix.col(j);

   访问矩阵的行和列的操作如下:

  

 1 #include <iostream>
 2 #include <eigen3/Eigen/Dense>
 3 
 4 using namespace Eigen;
 5 using namespace std;
 6 
 7 int main(int argc ,char** argv)
 8 {
 9     MatrixXf m(3,3);
10     m << 1,2,3,
11          4,5,6,
12          7,8,9;
13     cout<<"Here is the matrix m:"<<endl<<m<<endl;
14     cout<<"2nd Row: "<<m.row(1)<<endl;
15     m.col(2) += 3*m.col(0);
16     cout<<"After adding 4 times the first column into the third column,the matrix m is:\n";
17     cout<<m<<endl;
18     return 0;
19 }

 

Eigen 还提供了以下对 角点 等特殊块操作方法:

  

  矩阵的块操作:

  

  举例如下;

  

 1 #include <iostream>
 2 #include <eigen3/Eigen/Dense>
 3 
 4 using namespace Eigen;
 5 using namespace std;
 6 
 7 int main(int argc ,char** argv)
 8 {
 9     ArrayXf v(6);
10     v << 1,2,3,4,5,6;
11     cout<<"v.head(3) = "<<endl<<v.head(3)<<endl<<endl;
12     cout<<"v.tail<>() = "<<endl<<v.tail<3>()<<endl<<endl;
13     v.segemnt(1,4) *= 2;
14     cout<<"after v.segemt(1,4) *= 2,v="<<endl<<v<<endl;
15         
16     return 0;
17 }

  运行结果如下:

  

posted @ 2018-04-22 11:30  山里的小勇子  阅读(8639)  评论(0编辑  收藏  举报