MatrixXi mat(3,3); mat << 1, 2, 3, 4, 5, 6, 7, 8, 9; cout << "Here is the matrix mat:\n" << mat << endl; // This assignment shows the aliasing problem mat.bottomRightCorner(2,2) = mat.topLeftCorner(2,2); cout << "After the assignment, mat = \n" << mat << endl;
// shrink problem mat = mat.block(0,0,2,2); cout << "After shrink, mat = \n" << mat << endl;
// transpose problem Eigen::MatrixXi a(3,3); a << 1,2,3,4,5,6,7,8,9; cout <<"Here is the matrix a:\n" << a << endl; a = a.transpose(); cout << "After transpose matrtix a: \n" << a << endl;
实际的输出结果为
1 2 3 4 5 6 7 8 9 10 11
After shrink, mat = 128053282 01 Here is the matrix a: 123 456 789 After transpose matrtix a: 123 256 369
这些问题和之前所述是一致的
解决Aliasing问题
Eigen有自己的方式去使用一个temp来保证原矩阵的完整性,也就是使用.eval()来实现
1 2 3 4 5 6 7 8 9 10
// 使用eval,解决赋值问题 Eigen::MatrixXi mat2(3,3); mat2 << 1,2,3,4,5,6,7,8,9; cout <<"Here is the matrix mat2:\n" << mat2 << endl;
mat2.bottomRightCorner(2,2) = mat2.topLeftCorner(2,2).eval(); cout << "After the assignment, mat = \n" << mat2 << endl;