# 1. 举例

``````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;
``````

``````Here is the matrix mat:
1 2 3
4 5 6
7 8 9
After the assignment, mat =
1 2 3
4 1 2
7 4 1
``````

# 2. 解决混淆问题

Eigen需要把右值赋值为一个临时matrix/array，然后再将临时值赋值给左值，便可以解决混淆。eval()函数实现了这个功能。

``````MatrixXi mat(3,3);
mat << 1, 2, 3,   4, 5, 6,   7, 8, 9;
cout << "Here is the matrix mat:\\n" << mat << endl;
// The eval() solves the aliasing problem
mat.bottomRightCorner(2,2) = mat.topLeftCorner(2,2).eval();
cout << "After the assignment, mat = \\n" << mat << endl;
``````

``````Here is the matrix mat:
1 2 3
4 5 6
7 8 9
After the assignment, mat =
1 2 3
4 1 2
7 4 5
``````

Original function In-place function
DenseBase::reverse() DenseBase::reverseInPlace()
LDLT::solve() LDLT::solveInPlace()
LLT::solve() LLT::solveInPlace()
TriangularView::solve() TriangularView::solveInPlace()
DenseBase::transpose() DenseBase::transposeInPlace()

# 3. 混淆和component级的操作

``````MatrixXf mat(2,2);
mat << 1, 2,  4, 7;
cout << "Here is the matrix mat:\\n" << mat << endl << endl;
mat = 2 * mat;
cout << "After 'mat = 2 * mat', mat = \\n" << mat << endl << endl;
mat = mat - MatrixXf::Identity(2,2);
cout << "After the subtraction, it becomes\\n" << mat << endl << endl;
ArrayXXf arr = mat;
arr = arr.square();
cout << "After squaring, it becomes\\n" << arr << endl << endl;
// Combining all operations in one statement:
mat << 1, 2,  4, 7;
mat = (2 * mat - MatrixXf::Identity(2,2)).array().square();
cout << "Doing everything at once yields\\n" << mat << endl << endl;
``````

``````Here is the matrix mat:
1 2
4 7

After 'mat = 2 * mat', mat =
2  4
8 14

After the subtraction, it becomes
1  4
8 13

After squaring, it becomes
1  16
64 169

Doing everything at once yields
1  16
64 169
``````

# 4. 混淆和矩阵的乘法

``````// 单位阵
MatrixXf matA(2,2);
matA << 2, 0,  0, 2;
matA = matA * matA;
cout << matA;
``````

``````4 0
0 4
``````

# 5. 总结

• compnent级别的操作不存在混淆问题，比如标量乘法、matrix加法、array加法。
• 矩阵相乘，Eigen默认会解决混淆问题，如果你确定不会出现混淆，可以使用`noalias()`来提高效率。
• 在其他情况中，Eigen假设不存在混淆问题，因此当混淆出现时，Eigen会给出错误的结果，但是可以用`eval()`或者`xxxInPlace()`函数解决。

“Eigen教程(10)”