题目回顾:
假设有一个大的Eigen矩阵,我想把它的左上角3x3块提取出来,然后赋值为I3x3。编程实现.
解:提取大矩阵左上角3x3矩阵,有两种方式:
1、直接从0-2循环遍历大矩阵的前三行和三列
2、用矩阵变量.block(0,0,3,3)//从左上角00位置开始取3行3列
具体代码实现:
1 #include<iostream> 2 3 /*提取大矩阵左上角3x3矩阵,有两种方式: 4 1、直接从0-2循环遍历大矩阵的前三行和三列 5 2、用矩阵变量.block(0,0,3,3)//从左上角00位置开始取3行3列 6 */ 7 8 //包含Eigen头文件 9 #include<Eigen/Core> 10 #include<Eigen/Geometry> 11 12 #define MATRIX_SIZE 30 13 using namespace std; 14 15 int main(int argc,char **argv) 16 { 17 //设置输出小数点后3位 18 cout.precision(3); 19 Eigen::Matrix<double,MATRIX_SIZE, MATRIX_SIZE> matrix_NN = Eigen::MatrixXd::Random(MATRIX_SIZE,MATRIX_SIZE); 20 Eigen::Matrix<double,3,3>matrix_3d1 = Eigen::MatrixXd::Random(3,3);//3x3矩阵变量 21 Eigen::Matrix3d matrix_3d = Eigen::Matrix3d::Random();//两种方式都可以 22 /*方法1:循环遍历矩阵的三行三列 */ 23 for(int i = 0;i < 3; i ++){ 24 for(int j = 0 ;j < 3;j++){ 25 matrix_3d(i,j) = matrix_NN(i,j); 26 cout<<matrix_NN(i,j)<<" "; 27 } 28 cout<<endl; 29 } 30 matrix_3d = Eigen::Matrix3d::Identity(); 31 cout<<"赋值后的矩阵为:"<<matrix_3d<<endl; 32 33 /*方法2:用.block函数 */ 34 /* 35 cout<<"提取出来的矩阵块为:"<<endl; 36 cout<< matrix_NN.block(0,0,3,3) <<endl; 37 38 //提取后赋值为新的元素 39 matrix_3d = matrix_NN.block(0,0,3,3); 40 matrix_3d = Eigen::Matrix3d::Identity(); 41 cout<<"赋值后的矩阵为:"<<endl<<matrix_3d; 42 */ 43 return 0; 44 }